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


当前回答

从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);

其他回答

或者,使用扩展方法而不是单行:

public static T ToEnum<T>(this string enumString)
{
    return (T) Enum.Parse(typeof (T), enumString);
}

用法:

Color colorEnum = "Red".ToEnum<Color>();

OR

string color = "Red";
var colorEnum = color.ToEnum<Color>();

我更喜欢使用可为null的枚举类型变量。

var enumValue = (MyEnum?)enumInt;

if (!enumValue.HasValue)
{
    throw new ArgumentException(nameof(enumValue));
}

只要投它:

MyEnum e = (MyEnum)3;

使用Enum.IsDefined检查它是否在范围内:

if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }

以以下示例为例:

int one = 1;
MyEnum e = (MyEnum)one;

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

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

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

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

MyEnum someValue = (MyEnum)myIntValue;