【转】将String转换成Enum 以及Enum转换成String

一:  在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,这种方法不是最理想的,因为它会稍微有点慢,也许是设计的一个漏洞吧。
 
原文地址:https://www.cnblogs.com/sishierfei/p/2873398.html