一: 在C#中將String轉換成Enum:
object Enum.Parse(System.Type enumType, string value, bool ignoreCase);
所以,我們就可以在代碼中這么寫:
enum Colour { Red, Green, Blue } // ... Colour c = (Colour) Enum.Parse(typeof(Colour), "Red", true); Console.WriteLine("Colour Value: {0}", c.ToString()); // Picking an invalid colour throws an ArgumentException. To // avoid this, call Enum.IsDefined() first, as follows: string nonColour = "Polkadot"; if (Enum.IsDefined(typeof(Colour), nonColour)) c = (Colour) Enum.Parse(typeof(Colour), nonColour, true); else MessageBox.Show("Uh oh!");
二: 在C#中將轉Enum換成String:
object Enum.GetName(typeof(enumType), value);
所以,在以上的例子中我們就可以這樣寫:
string c2string=Enum.GetName(typeof(Colour), c);
注:有意思的是,我注意到 Enum.IsDefined()沒有提供ignoreCase 的變量,如果你不知道大小寫是不是正確,好像你只能去用Parse方法去轉換了,然后捕獲ArgumentException,這種方法不是最理想的,因為它會稍微有點慢,也許是設計的一個漏洞吧。