可以指定所有整型(不包括 char 類型)為枚舉值的類型, 下面是指定為 byte:
using System;
class MyClass
{
enum MyEnum : byte { AA, BB, CC, DD };
static void Main()
{
string[] Names = Enum.GetNames(typeof(MyEnum));
foreach (string s in Names)
{
Console.WriteLine(s); // AA/BB/CC/DD
}
byte[] Values = (byte[])Enum.GetValues(typeof(MyEnum));
foreach (byte n in Values)
{
Console.WriteLine(n); // 0/1/2/3
}
Console.ReadKey();
}
}
枚舉經常這樣用:
using System;
class MyClass
{
enum MyEnum
{
AA = 0x0,
BB = 0x1,
CC = 0x2,
DD = 0x4,
EE = 0x8,
FF = 0x10,
GG = 0x20,
HH = 0x40
}
static void Main()
{
MyEnum es = MyEnum.CC | MyEnum.DD;
Console.WriteLine(es); // 6
Console.ReadKey();
}
}