C#编程中枚举类型的使用教程

2019-12-30 11:34:33王冬梅

枚举类型作为位标志
可以使用枚举类型定义位标志,从而使该枚举类型的实例可以存储枚举数列表中定义的值的任意组合。(当然,某些组合在您的程序代码中可能没有意义或不允许使用。)
创建位标志枚举的方法是应用 System.FlagsAttribute 特性并适当定义一些值,以便可以对这些值执行 AND、OR、NOT 和 XOR 按位运算。在位标志枚举中包含一个值为零(表示“未设置任何标志”)的命名常量。如果零值不表示“未设置任何标志”,则请不要为标志指定零值。
在下面的示例中,定义了 Days 枚举的另一个版本,命名为 Days2。 Days2 具有 Flags 特性,且它的每个值都是 2 的若干次幂,指数依次递增。这样,您将能够创建值为 Days2.Tuesday 和 Days2.Thursday 的 Days2 变量。


[Flags]
enum Days2
{
  None = 0x0,
  Sunday = 0x1,
  Monday = 0x2,
  Tuesday = 0x4,
  Wednesday = 0x8,
  Thursday = 0x10,
  Friday = 0x20,
  Saturday = 0x40
}
class MyClass
{
  Days2 meetingDays = Days2.Tuesday | Days2.Thursday;
}

若要在某个枚举上设置标志,请使用按位 OR 运算符,如下面的示例所示:


// Initialize with two flags using bitwise OR.
meetingDays = Days2.Tuesday | Days2.Thursday;

// Set an additional flag using bitwise OR.
meetingDays = meetingDays | Days2.Friday;

Console.WriteLine("Meeting days are {0}", meetingDays);
// Output: Meeting days are Tuesday, Thursday, Friday

// Remove a flag using bitwise XOR.
meetingDays = meetingDays ^ Days2.Tuesday;
Console.WriteLine("Meeting days are {0}", meetingDays);
// Output: Meeting days are Thursday, Friday

若要确定是否设置了特定标志,请使用按位 AND 运算,如下面的示例所示:


// Test value of flags using bitwise AND.
bool test = (meetingDays & Days2.Thursday) == Days2.Thursday;
Console.WriteLine("Thursday {0} a meeting day.", test == true ? "is" : "is not");
// Output: Thursday is a meeting day.


使用 System.Enum 方法发现和操作枚举值
所有枚举都是 System.Enum 类型的实例。不能从 System.Enum 派生新类,但可以使用它的方法发现有关枚举实例中的值的信息以及操作这些值。


string s = Enum.GetName(typeof(Days), 4);
Console.WriteLine(s);

Console.WriteLine("The values of the Days Enum are:");
foreach (int i in Enum.GetValues(typeof(Days)))
  Console.WriteLine(i);

Console.WriteLine("The names of the Days Enum are:");
foreach (string str in Enum.GetNames(typeof(Days)))
  Console.WriteLine(str);