Enum.IsDefined 的用法

 

syntax:
Enum.IsDefined(Type enumType, object value)

說明:
Enum.IsDefined 方法是用來檢查要轉換的變數是否在 Enum 的範圍之內,
範例如下。

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
string day = "Thursday";

// 檢查要轉換的變數是否在Enum的範圍之內
if (Enum.IsDefined(typeof(DayOfWeek), day))
Console.WriteLine(day); // output Thursday

// Convert string to enum
DayOfWeek dayOfWeek = Enum.Parse<DayOfWeek>(day);

// Convert enum to string
Console.WriteLine(Enum.GetName(dayOfWeek)); // output Thursday

// Convert enum to int
Console.WriteLine(dayOfWeek.GetHashCode()); // output 4

public enum DayOfWeek
{
/// <summary>
/// 星期日
/// </summary>
Sunday,

/// <summary>
/// 星期一
/// </summary>
Monday,

/// <summary>
/// 星期二
/// </summary>
Tuesday,

/// <summary>
/// 星期三
/// </summary>
Wednesday,

/// <summary>
/// 星期四
/// </summary>
Thursday,

/// <summary>
/// 星期五
/// </summary>
Friday,

/// <summary>
/// 星期六
/// </summary>
Saturday
}