In .NET Core and .NET >4 there is a generic parse method :
(在.NET Core和.NET> 4中, 有一个通用的解析方法 :)
Enum.TryParse("Active", out StatusEnum myStatus);
This also includes C#7's new inline out
variables, so this does the try-parse, conversion to the explicit enum type and initialises+populates the myStatus
variable.
(这也包括C#7的新型直列out
变量,所以这样做的尝试,解析,转换为明确枚举类型和初始化+填充myStatus
变量。)
If you have access to C#7 and the latest .NET this is the best way.
(如果您可以访问C#7和最新的.NET,则这是最好的方法。)
Original Answer (原始答案)
In .NET it's rather ugly (until 4 or above):
(在.NET中,它相当难看(直到4或更高版本):)
StatusEnum MyStatus = (StatusEnum) Enum.Parse(typeof(StatusEnum), "Active", true);
I tend to simplify this with:
(我倾向于用:)
public static T ParseEnum<T>(string value)
{
return (T) Enum.Parse(typeof(T), value, true);
}
Then I can do:
(然后我可以做:)
StatusEnum MyStatus = EnumUtil.ParseEnum<StatusEnum>("Active");
One option suggested in the comments is to add an extension, which is simple enough:
(注释中建议的一个选项是添加扩展名,该扩展名很简单:)
public static T ToEnum<T>(this string value)
{
return (T) Enum.Parse(typeof(T), value, true);
}
StatusEnum MyStatus = "Active".ToEnum<StatusEnum>();
Finally, you may want to have a default enum to use if the string cannot be parsed:
(最后,如果无法解析字符串,则可能需要使用默认的枚举:)
public static T ToEnum<T>(this string value, T defaultValue)
{
if (string.IsNullOrEmpty(value))
{
return defaultValue;
}
T result;
return Enum.TryParse<T>(value, true, out result) ? result : defaultValue;
}
Which makes this the call:
(这使得此调用:)
StatusEnum MyStatus = "Active".ToEnum(StatusEnum.None);
However, I would be careful adding an extension method like this to string
as (without namespace control) it will appear on all instances of string
whether they hold an enum or not (so 1234.ToString().ToEnum(StatusEnum.None)
would be valid but nonsensical) .
(但是,我会小心地向string
添加这样的扩展方法,因为(没有名称空间控制)它会出现在string
所有实例上,无论它们是否具有枚举(因此1234.ToString().ToEnum(StatusEnum.None)
都会是有效的,但毫无意义)。)
It's often be best to avoid cluttering Microsoft's core classes with extra methods that only apply in very specific contexts unless your entire development team has a very good understanding of what those extensions do. (通常最好避免使用仅适用于非常特定的上下文的额外方法来使Microsoft的核心类混乱,除非整个开发团队对这些扩展的工作有很好的了解。)