参考文献:
1.https://docs.microsoft.com/zh-cn/dotnet/csharp/language-reference/keywords/enum
2.https://docs.microsoft.com/zh-cn/dotnet/csharp/programming-guide/enumeration-types
枚举:
1.默认情况下,枚举中每个元素的基础类型都为 int。
2.如果未为枚举器列表中的元素指定值,则值将自动按 1 递增。
3.已批准的枚举类型有 byte、sbyte、short、ushort、int、uint, long 或 ulong。
4.枚举数名称中不能含有空格。
5.枚举成员采用驼峰命名
6.若要在枚举上设置标志,请使用按位 OR
运算符,如以下示例所示:// Initialize with two flags using bitwise OR. meetingDays = Days.Tuesday | Days.Thursday;
7.若要确定是否设置了特定标志,请使用按位 AND
运算,如以下示例所示:// Test value of flags using bitwise AND. bool test = (meetingDays & Days.Thursday) == Days.Thursday;
8.使用 System.Enum 方法来发现和操作枚举值
[Flags] enum Days { None = 0x0, Sunday = 0x1, Monday = 0x2, Tuesday = 0x4, Wednesday = 0x8, Thursday = 0x10, Friday = 0x20, Saturday = 0x40 } class MyClass { Days meetingDays = Days.Tuesday | Days.Thursday; }
// Initialize with two flags using bitwise OR. 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.
8.
string s = Enum.GetName(typeof(Day), 4); Console.WriteLine(s); Console.WriteLine("The values of the Day Enum are:"); foreach (int i in Enum.GetValues(typeof(Day))) Console.WriteLine(i); Console.WriteLine("The names of the Day Enum are:"); foreach (string str in Enum.GetNames(typeof(Day))) Console.WriteLine(str);