规则:枚举应该具有零值
违反此规则的情况:
未应用 System.FlagsAttribute 的枚举没有定义为零值的成员;或者应用了 FlagsAttribute 的枚举虽然定义了零值的成员,但其名称不是"None",或者该枚举定义了多个为零值的成员。
FlagsAttribute: 指示可以将枚举作为位(bit)处理,能进行位运算。
位域通常用于由可组合出现的元素组成的列表,而枚举常数通常用于由互相排斥的元素组成的列表。 因此,位域设计为通过按位"或"运算组合来生成未命名的值,而枚举常数则不是。
例如ModifierKeys枚举就有这个attribute, 表示有多个modifierkey同时按下。
protected override void OnPreviewKeyDown(KeyEventArgs e)
Console.WriteLine(Keyboard.Modifiers.ToString() + " " + (int)Keyboard.Modifiers);
1,用 2 的幂(即 1、2、4、8 等)定义枚举常量。 这意味着组合的枚举常量中的各个标志都不重叠。
如果创建的是值枚举而不是标志枚举,创建 None 枚举常量仍十分有用。 原因是在默认情况下,公共语言运行时会将用于枚举的内存初始化为零。 因此,如果不定义值为零的常量,则枚举在创建时将包含非法值。
如果明显存在应用程序需要表示的默认情况,请考虑使用值为零的枚举常量表示默认值。
// Example of the FlagsAttribute attribute.
// Define an Enum without FlagsAttribute.
// Define an Enum with FlagsAttribute.
"This example of the FlagsAttribute attribute \n" +
"generates the following output." );
"\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( ) );
"\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