一、枚举定义:

enum 关键字用于声明枚举,即一种由一组称为枚举数列表的命名常量组成的独特类型。

二、枚举规则:

1. 默认情况下,第一个枚举数的值为 0,后面每个枚举数的值依次递增 1;也可强制元素序列从设定值而不是 0 开始

2. 准许使用的枚举类型有 byte、sbyte、short、ushort、int、uint、long 或 ulong。

3. 枚举类型作为位标志,应用 System.FlagsAttribute 特性,每个值都是 2 的若干次幂,可以对这些值执行 AND、OR、NOT 和 XOR 按位运算;避免标志指定零值。

三、枚举例子:

1: using System;

2: using System.Collections.Generic;

3: using System.Linq;

4: using System.Text;

5:

6: namespace CSharp.Enum

7: {

8:

9: [Flags]

10: enum Days2

11: {

12: None = 0x0,

13: Sunday = 0x1,

14: Monday = 0x2,

15: Tuesday = 0x4,

16: Wednesday = 0x8,

17: Thursday = 0x10,

18: Friday = 0x20,

19: Saturday = 0x40

20: }

21:

22: class Program

23: {

24: static void Main(string[] args)

25: {

26: // Initialize with two flags using bitwise OR.

27: Days2 meetingDays = Days2.Tuesday | Days2.Thursday | Days2.Friday;

28: Console.WriteLine("Meeting days are {0}", meetingDays);

29:

30: // Remove a flag using bitwise XOR.

31: meetingDays = meetingDays ^ Days2.Tuesday;

32: Console.WriteLine("Meeting days are {0}", meetingDays);

33:

34: //若要确定是否设置了特定标志,请使用按位 AND 运算

35: bool test = (meetingDays & Days2.Thursday) == Days2.Thursday;

36: Console.WriteLine("Thursday {0} a meeting day.", test == true ? "is" : "is not");

37:

38: string saturday=System.Enum.GetName(typeof(Days2), 0x40);

39: Console.WriteLine("0x40 's Name is {0}",saturday);

40:

41: Console.WriteLine("The values of the Days2 Enum are:");

42: foreach (int i in System.Enum.GetValues(typeof(Days2)))

43: {

44: Console.WriteLine(i);

45: }

46:

47: Console.WriteLine("The names of the Days2 Enum are:");

48: foreach (string str in System.Enum.GetNames(typeof(Days2)))

49: Console.WriteLine(str);

50:

51: Days2 saturday2= (Days2)System.Enum.Parse(typeof(Days2), "Saturday");

52: if(System.Enum.IsDefined(typeof(Days2),saturday2))

53: {

54: Console.WriteLine(" \"Saturday\" 转换为对象 Days2.Saturday ");

55: }

56:

57: }

58: }

59: }附件:http://down.51cto.com/data/2362495