c#枚舉轉化示例大全,數字或字符串轉枚舉

 

c#枚舉轉化示例大全,數字或字符串轉枚舉,本文重點舉例說明C#枚舉的用法,數字轉化爲枚舉、枚舉轉化爲數字及其枚舉數值的判斷,以下是具體的示例:

先舉兩個簡單的例子,然後再詳細的舉例說明:

字符串轉換成枚舉:DayOfWeek week= (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "Friday");
數字轉換成枚舉:DayOfWeek week= (DayOfWeek)5;  //Friday
具體的示例:
定義枚舉: 
public enum DisplayType 

  All=10, 
  Up=20, 
  Down=30 
}

 

1.數值轉化 
(1)字符轉化爲枚舉 
string str="up"; 
DisplayType displayType; 
displayType=(DisplayType)System.Enum.Parse(typeof(DisplayType),str,true); 
Response.Write(displayType.ToString());

結果是:Up 
Enum.Parse 方法第3個參數,如果爲 true,則忽略大小寫;否則考慮大小寫。

(2)數字轉化爲枚舉 
int i=30; 
DisplayType displayType; 
displayType=(DisplayType)System.Enum.Parse(typeof(DisplayType),i.ToString()); 
Response.Write(displayType.ToString()); 
結果是:Down 
(3)枚舉轉化爲字符 
DisplayType displayType=DisplayType.Down; 
string str=displayType.ToString(); 
Response.Write(str); 
結果是:Down

(4)枚舉轉化爲數字 
方法一: 
DisplayType displayType=DisplayType.Down; 
int i=Convert.ToInt32(displayType.ToString("d")); 
Response.Write(i.ToString());

或者:(int)Enum.Parse(typrof(DisplayType),"Down")
結果是:30

方法二: 
DisplayType displayType=DisplayType.Down; 
int i=((IConvertible)((System.Enum)displayType)).ToInt32(null); 
Response.Write(i.ToString()); 
結果是:30

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章