c#枚舉轉化示例大全,數字或字符串轉枚舉,本文重點舉例說明C#枚舉的用法,數字轉化爲枚舉、枚舉轉化爲數字及其枚舉數值的判斷,如下是具體的示例:c#
先舉兩個簡單的例子,而後再詳細的舉例說明:ide
字符串轉換成枚舉:DayOfWeek week= (DayOfWeek)Enum.Parse(typeof(DayOfWeek), "Friday");
數字轉換成枚舉:DayOfWeek week= (DayOfWeek)5; //Friday
具體的示例:
定義枚舉:
public enum DisplayType
{
All=10,
Up=20,
Down=30
}spa
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,則忽略大小寫;不然考慮大小寫。string
(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);
結果是:Downit
(4)枚舉轉化爲數字
方法一:
DisplayType displayType=DisplayType.Down;
int i=Convert.ToInt32(displayType.ToString("d"));
Response.Write(i.ToString());class
或者:(int)Enum.Parse(typrof(DisplayType),"Down")
結果是:30方法
方法二:
DisplayType displayType=DisplayType.Down;
int i=((IConvertible)((System.Enum)displayType)).ToInt32(null);
Response.Write(i.ToString());
結果是:30margin