下面範例列出 enum 對 int、string 型別的互轉,與取 Description 描述名稱的方式。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
| using System.ComponentModel; using System.Reflection;
Console.WriteLine((DayOfWork)0); Console.WriteLine();
Console.WriteLine((int)DayOfWork.Monday); Console.WriteLine();
Console.WriteLine(DayOfWork.Tuesday.ToString()); Console.WriteLine();
Console.WriteLine(Enum.Parse(typeof(DayOfWork), "Wednesday")); Console.WriteLine();
Console.WriteLine(GetDescriptionText(DayOfWork.Thursday)); Console.WriteLine();
foreach (string en in Enum.GetNames(typeof(DayOfWork))) Console.WriteLine(en); Console.WriteLine();
foreach (int v in Enum.GetValues(typeof(DayOfWork))) Console.WriteLine(v); Console.WriteLine();
string GetDescriptionText(Enum source) { FieldInfo fi = source.GetType().GetField(source.ToString()); DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false); if (attributes.Length > 0) return attributes[0].Description; else return source.ToString(); }
enum DayOfWork { [Description("星期日")] Sunday = 0,
[Description("星期一")] Monday = 1,
[Description("星期二")] Tuesday = 2,
[Description("星期三")] Wednesday = 3,
[Description("星期四")] Thursday = 4,
[Description("星期五")] Friday = 5,
[Description("星期六")] Saturday = 6 }
|