小编典典

如何将int枚举为枚举?

c#

如何在C#中将int其强制转换为enum


阅读 260

收藏
2020-05-19

共1个答案

小编典典

从字符串:

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);
2020-05-19