C#如何将字符串转换为枚举类型

其中我们将使用 Enum.Parse() 方法将字符串转换为枚举。
Enum 关键字用于声明枚举,一种独特的类型,由一组称为枚举的命名常量组成。
它是这样声明的:

enum Colors {Red, Green, Yellow, Orange};

在这个枚举中,红色是0,Geen为1,黄色为2等。
枚举器可以具有初始化器来覆盖默认值。

例如:

enum colors {Red=2,Green,Yellow,Orange};

在该枚举中,元素序列从2开始而不是从0开始。

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace ConsoleApplication5

{

  class Program

  {

      enum Colors { None = 0, Red = 1, Green = 2, Blue = 4 };

      static void Main(string[] args)

      {

          string[] colorStrings = { "0", "2", "8", "blue", "Blue", "Yellow", "Red, Green" };

          foreach (string colorString in colorStrings)

          {

              try

              {

                  Colors colorValue = (Colors)Enum.Parse(typeof(Colors), colorString);

                  if (Enum.IsDefined(typeof(Colors), colorValue) | colorValue.ToString().Contains(","))

                      Console.WriteLine("Converted '{0}' to {1}.", colorString, colorValue.ToString());

                  else

                      Console.WriteLine("{0} is not an underlying value of the Colors enumeration.", colorString);

              }

              catch (ArgumentException)

              {

                  Console.WriteLine("'{0}' is not a member of the Colors enumeration.", colorString);

              }

          }

          Console.ReadLine();

      }

  }

}
日期:2020-04-11 22:50:20 来源:oir作者:oir