如何在C#中将int转换为枚举?


当前回答

从字符串:(Enum.Parse已过期,请使用Enum.TryParse)

enum Importance
{}

Importance importance;

if (Enum.TryParse(value, out importance))
{
}

其他回答

对于字符串,可以执行以下操作:

var result = Enum.TryParse(typeof(MyEnum), yourString, out yourEnum) 

并确保检查结果以确定转换是否失败。

对于int,可以执行以下操作:

MyEnum someValue = (MyEnum)myIntValue;

您只需执行以下操作:

int intToCast = 1;
TargetEnum f = (TargetEnum) intToCast ;

为了确保只计算正确的值​​否则可以抛出异常:

int intToCast = 1;
if (Enum.IsDefined(typeof(TargetEnum), intToCast ))
{
    TargetEnum target = (TargetEnum)intToCast ;
}
else
{
   // Throw your exception.
}

请注意,使用IsDefined的成本很高,甚至不仅仅是强制转换,因此决定是否使用它取决于您的实现。

有时您有一个MyEnum类型的对象。喜欢

var MyEnumType = typeof(MyEnum);

然后:

Enum.ToObject(typeof(MyEnum), 3)

向Enum转换和从Enum转换的不同方式

enum orientation : byte
{
 north = 1,
 south = 2,
 east = 3,
 west = 4
}

class Program
{
  static void Main(string[] args)
  {
    orientation myDirection = orientation.north;
    Console.WriteLine(“myDirection = {0}”, myDirection); //output myDirection =north
    Console.WriteLine((byte)myDirection); //output 1

    string strDir = Convert.ToString(myDirection);
        Console.WriteLine(strDir); //output north

    string myString = “north”; //to convert string to Enum
    myDirection = (orientation)Enum.Parse(typeof(orientation),myString);


 }
}

从int:

YourEnum foo = (YourEnum)yourInt;

从字符串:

YourEnum foo = (YourEnum) Enum.Parse(typeof(YourEnum), yourString);

// The foo.ToString().Contains(",") check is necessary for 
// enumerations marked with a [Flags] attribute.
if (!Enum.IsDefined(typeof(YourEnum), foo) && !foo.ToString().Contains(","))
{
    throw new InvalidOperationException(
        $"{yourString} is not an underlying value of the YourEnum enumeration."
    );
}

从一个数字:

YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum), yourInt);