TIPS-Conversion Between enum, int And string
0 |
.NET中的Enumerate可以提高程式的嚴謹性及可讀性,我最愛的一個例子是DateTime的DayOfWork Enumeration。
if (DateTime.Now.DayOfWeek==DayOfWeek.Friday)是不是比DateTime.Now.DayOfWeek==5更容易閱讀呢? 而當要求使用者傳入星期幾作為參數時,也不必擔心User傳入-1 或18來搗蛋。
不過,在某些時候,我們還是需要將星期三轉成數字3,或是將"Sunday"解讀成為DayOfWeek.Sunday。廢話不多說,請大家看以下的程式,它完整地示範了如何進行int<->enum, string<->enum間的轉換:
int i = 3;
//Convert From Integer to Enum
DayOfWeek dw = (DayOfWeek)Enum.ToObject(typeof(DayOfWeek), i);
Console.WriteLine(string.Format("int [{0}] -> enum [{1}]", i, dw));
//Convert From Enum To Integer
dw = DayOfWeek.Thursday;
i = (int)dw;
Console.WriteLine(string.Format("enum [{1}] -> int [{0}]", i, dw));
//Convert From Enum To String
dw = DayOfWeek.Friday;
string s = dw.ToString();
Console.WriteLine(string.Format("enum [{1}] -> string '{0}'", s, dw));
//Convert From String To Enum
s = "Sunday";
dw = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), s);
Console.WriteLine(string.Format("string '{0}' -> enum [{1}]", s, dw));
執行結果如下:
int [3] -> enum [Wednesday]
enum [Thursday] -> int [4]
enum [Friday] -> string 'Friday'
string 'Sunday' -> enum [Sunday]
Comments
Be the first to post a comment