2012-03-17
今天我们来讲一下枚举。
enum 关键字用于声明枚举,即一种由一组称为枚举数列表的命名常量组成的独特类型。
The enum keyword is used to declare an enumeration, a distinct type that consists of a set of named constants called the enumerator list.(in MSDN)
Example1:
1 namespace ConsoleApplication1 2 { 3 enum Days : byte 4 { 5 Sunday = 1, 6 Monday, 7 Tuesday, 8 Wednesday, 9 Thursday, 10 Friday, 11 Saturday 12 } 13 14 class Program 15 { 16 static void Main(string[] args) 17 { 18 } 19 } 20 }
上面一段代码,声明了一个名字为Days的枚举类型,每个枚举值的类型指定为byte。枚举支持类型byte, sbyte, short, ushort, int, uint, long, or long。同时,我们改变了它的初始化值(默认为0)。但是其实.Net推荐我们使用默认值。
Example2:
1 namespace ConsoleApplication1 2 { 3 enum Days : byte 4 { 5 Sunday = 1, 6 Monday, 7 Tuesday, 8 Wednesday, 9 Thursday, 10 Friday, 11 Saturday 12 } 13 14 class Program 15 { 16 static void Main(string[] args) 17 { 18 Days day = (Days)9; 19 Days day2 = (Days)6; 20 Console.WriteLine(day); 21 Console.WriteLine(day2); 22 } 23 } 24 }
稍作修改。我们发现对day的赋值是一个越界的值,但是编译器没有报错。我们看一下输出结果:
9
Friday
因为是一个越界的值,没有正常输出,而是输出一个9,而第二个正常输出Friday。这样的赋值编译器没有报错,所以将错误隐藏到了使用的时候。可以假设,如果我们用赋了越界值的枚举变量去做判断,如果我们直接使用它时,结果我们不得而知。
Example3:
namespace ConsoleApplication1 { [Flags] enum Days { None = 0x0, Sunday = 0x1, Monday = 0x2, Tuesday = 0x4, Wednesday = 0x8, Thursday = 0x10, Friday = 0x20, Saturday = 0x40 } class Program { static void Main(string[] args) { // Initialize with two flags using bitwise OR. Days meetingDays = Days.Tuesday | Days.Thursday; // Set an additional flag using bitwise OR. meetingDays = meetingDays | Days.Friday; Console.WriteLine("Meeting days are {0}", meetingDays); // Output: Meeting days are Tuesday, Thursday, Friday // Remove a flag using bitwise XOR. meetingDays = meetingDays ^ Days.Tuesday; Console.WriteLine("Meeting days are {0}", meetingDays); // Output: Meeting days are Thursday, Friday // Test value of flags using bitwise AND. bool test = (meetingDays & Days.Thursday) == Days.Thursday; Console.WriteLine("Thursday {0} a meeting day.", test == true ? "is" : "is not"); // Output: Thursday is a meeting day. } } }
使用enum作为位标志,然后可以使用位运算做一个操作,使enum更能让人能够理解它的用途用意。