在int中枚举枚举在C#中枚举

如何将int为C#中的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);

只是施展它:

MyEnum e = (MyEnum)3;

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

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

或者,使用扩展方法而不是单行命令:

public static T ToEnum<T>(this string enumString)
{
    return (T) Enum.Parse(typeof (T), enumString);
}

用法:

Color colorEnum = "Red".ToEnum<Color>();

要么

string color = "Red";
var colorEnum = color.ToEnum<Color>();
链接地址: http://www.djcxy.com/p/511.html

上一篇: Cast int to enum in C#

下一篇: How do I check if a list is empty?