小编典典

如何将 int 转换为枚举?

javascript

如何在 C# 中将anint强制转换为 an enum


阅读 139

收藏
2022-01-13

共1个答案

小编典典

从一个整数:

YourEnum foo = (YourEnum)yourInt;

从一个字符串:

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.")
}

更新:

从号码你也可以

YourEnum foo = (YourEnum)Enum.ToObject(typeof(YourEnum) , yourInt);
2022-01-13