在int C中枚举枚举
问题描述:
如何将 int
转换为C#中的枚举
?
How can an int
be cast to an enum
in C#?
答
从字符串:
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);