如何将int转为enum?

在C#中,如何将 "int "转为 "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);
评论(19)

就投吧。

MyEnum e = (MyEnum)3;

你可以用Enum.IsDefined检查它是否在范围内。

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

以下面的例子为例:

评论(0)