先定義一個枚舉類型
public enum PropertyType { 小學 = 0, 初中, 高中,大學 };
?
int ->enum?
?????? int d=2; ????
????? ?PropertyType? a=(PropertyType)d;
int <- enum????????
???? ? PropertyType? d = PropertyType.小學; ??????
????? ?int a = Convert.ToInt32(d);
Enum類有關的方法
Enum.Parse 方法 (Type, String)
將一個或多個枚舉常數的名稱或數字值的字符串表示轉換成等效的枚舉對象。
public static Object Parse(Type enumType,string value )參數 enumType類型:System.Type 枚舉類型。
value類型:System.String 包含要轉換的值或名稱的字符串。返回值類型:System.Object enumType 類型的對象,其值由 value 表示。
?
如果我們有兩個enum,
1 | public ?enum ?Colors {Red, Green, Blue} |
2 | ? |
3 | public ?enum ?BgColors {Red, Black, Green, Blue } |
?
看起來差不多。
有一天有需要把一個變成另一個來用。可能會寫成這樣:
1 | Colors font_color = Colors.Blue; |
2 | BgColor bg = (BgColor)font_color; |
看起來可以,編譯也對。但實際上是不對的,因為實際上是轉成enum所代表的int,對應的結果往往不是我們想要的。
正確的作法是?
1 | Colors font_color = Colors.Blue; |
2 | (BgColor)Enum.Parse( typeof (BgColor), font_color.ToString()); |
?這是一種很簡單的理念,但常常寫成上面的寫法。但日后如果其中之一有變,造成順序有更改的話,就會出現錯誤。
?
Enum.GetName 方法
指定枚舉中檢索具有指定值的常數的名稱。
public static string GetName(Type enumType,Object value )enumType 類型:System.Type 枚舉類型。value 類型:System.Object 特定枚舉常數的值(根據其基礎類型)。返回值 類型:System.String 一個字符串,其中包含 enumType 中值為 value 的枚舉常數的名稱;如果沒有找到這樣的常數,則為 null。
?
Enum.GetNames 方法
檢索指定枚舉中常數名稱的數組。
?


public static string[] GetNames(Type enumType )參數 enumType 類型:System.Type 枚舉類型。返回值 類型:System.String[] enumType 的常數名稱的字符串數組。
?
?
?
?
?