枚举应该具有零值

规则:枚举应该具有零值

违反此规则的情况:

未应用 System.FlagsAttribute 的枚举没有定义为零值的成员;或者应用了 FlagsAttribute 的枚举虽然定义了零值的成员,但其名称不是"None",或者该枚举定义了多个为零值的成员。

FlagsAttribute: 指示可以将枚举作为位(bit)处理,能进行位运算。

位域通常用于由可组合出现的元素组成的列表,而枚举常数通常用于由互相排斥的元素组成的列表。 因此,位域设计为通过按位""运算组合来生成未命名的值,而枚举常数则不是。

例如ModifierKeys枚举就有这个attribute, 表示有多个modifierkey同时按下。

看下面的代码:

protected override void OnPreviewKeyDown(KeyEventArgs e)

{

base.OnPreviewKeyDown(e);

Console.WriteLine(Keyboard.Modifiers.ToString() + " " + (int)Keyboard.Modifiers);

}

按不同的键或组合键,输出如下:

Control 2

Alt 1

Control 2

Alt, Control 3

Control 2

Control, Shift 6

Control 2

Control, Shift 6

Alt, Control, Shift 7

 

 

应用了Flags的枚举有以下规则:

1,用 2 的幂(即 1248 等)定义枚举常量。 这意味着组合的枚举常量中的各个标志都不重叠。

2,测试数值中是否已设置标志的一种简便方法为:在数值和标志枚举常量之间执行按位""操作,这种方法会将数值中与标志不对应的所有位都设置为零,然后测试该操作的结果是否等于该标志枚举常量。3,将 None 用作值为零的标志枚举常量的名称。 在按位 AND 运算中,不能使用 None 枚举常量测试标志,因为所得的结果始终为零。

如果创建的是值枚举而不是标志枚举,创建 None 枚举常量仍十分有用。 原因是在默认情况下,公共语言运行时会将用于枚举的内存初始化为零。 因此,如果不定义值为零的常量,则枚举在创建时将包含非法值。

如果明显存在应用程序需要表示的默认情况,请考虑使用值为零的枚举常量表示默认值。

 

// Example of the FlagsAttribute attribute.

using System;

class FlagsAttributeDemo

{

// Define an Enum without FlagsAttribute.

enum SingleHue : short

{

Black = 0,

Red = 1,

Green = 2,

Blue = 4

};

 

// Define an Enum with FlagsAttribute.

[FlagsAttribute]

enum MultiHue : short

{

Black = 0,

Red = 1,

Green = 2,

Blue = 4

};

 

static void Main( )

{

Console.WriteLine(

"This example of the FlagsAttribute attribute \n" +

"generates the following output." );

Console.WriteLine(

"\nAll possible combinations of values of an \n" +

"Enum without FlagsAttribute:\n" );

 

// Display all possible combinations of values.

for( int val = 0; val <= 8; val++ )

Console.WriteLine( "{0,3} - {1}",

val, ( (SingleHue)val ).ToString( ) );

 

Console.WriteLine(

"\nAll possible combinations of values of an \n" +

"Enum with FlagsAttribute:\n" );

 

// Display all possible combinations of values.

// Also display an invalid value.

for( int val = 0; val <= 8; val++ )

Console.WriteLine( "{0,3} - {1}",

val, ( (MultiHue)val ).ToString( ) );

}

}

 

/*

This example of the FlagsAttribute attribute

generates the following output.

 

All possible combinations of values of an

Enum without FlagsAttribute:

 

0 - Black

1 - Red

2 - Green

3 - 3

4 - Blue

5 - 5

6 - 6

7 - 7

8 - 8

 

All possible combinations of values of an

Enum with FlagsAttribute:

数值可以转换成唯一的一个单个枚举值,或者组合。

0 - Black

1 - Red

2 - Green

3 - Red, Green

4 - Blue

5 - Red, Blue

6 - Green, Blue

7 - Red, Green, Blue

8 - 8

*/

 

 

原文地址:https://www.cnblogs.com/bear831204/p/2132310.html