enum 的轉換

 

下面範例列出 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
// int to enum
using System.ComponentModel;
using System.Reflection;

Console.WriteLine((DayOfWork)0); // output:Sunday
Console.WriteLine();

// enum to int
Console.WriteLine((int)DayOfWork.Monday); // output:1
Console.WriteLine();

// enum to string
Console.WriteLine(DayOfWork.Tuesday.ToString()); // output:Tuesday
Console.WriteLine();

// string to enum
Console.WriteLine(Enum.Parse(typeof(DayOfWork), "Wednesday")); // output:Wednesday
Console.WriteLine();

// 取 Description 描述名稱
Console.WriteLine(GetDescriptionText(DayOfWork.Thursday)); // output:星期四
Console.WriteLine();

// 列出 enum DayOfWork 所有名稱
foreach (string en in Enum.GetNames(typeof(DayOfWork)))
Console.WriteLine(en);
Console.WriteLine();
// output:
// Sunday
// Monday
// Tuesday
// Wednesday
// Thursday
// Friday
// Saturday

// 列出 enum DayOfWork 所有值
foreach (int v in Enum.GetValues(typeof(DayOfWork)))
Console.WriteLine(v);
Console.WriteLine();
// output:
// 0
// 1
// 2
// 3
// 4
// 5
// 6

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
}