如何在 C# 中将anint强制转换为 an enum?
anint
an enum
从一个整数:
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);