协慌网

登录 贡献 社区

在 C#中将 int 转换为枚举

如何将int为 C#中的enum

答案

从字符串:

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

来自 int:

YourEnum foo = (YourEnum)yourInt;

更新:

从数字你也可以

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

只是施展它:

MyEnum e = (MyEnum)3;

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

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

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

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

用法:

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

要么

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