如何将字符串转换为C#中的枚举? [英] How should I convert a string to an enum in C#?

查看:114
本文介绍了如何将字符串转换为C#中的枚举?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我有一个包含枚举值的HTML选择标签,最好的方法是将字符串转换为C#中的枚举值。当页面发布时,我想要获取值(将以字符串的形式),并将其转换为枚举值。



在理想状态下世界,我可以这样做:

  StatusEnum MyStatus = StatusEnum.Parse(Active); 

但这不是有效的代码。

解决方案

在.NET Core和.NET> 4 有一个通用的解析方法

  Enum.TryParse 活动,显示StatusEnum myStatus); 

这也包括C#7的新内嵌 out 变量,所以这样做是解析,转换为显式枚举类型,并初始化+填充 myStatus 变量。



如果您有权访问C#7和最新的.NET这是最好的方法。



原始答案



在.NET中,它比较丑陋(直到4或以上):

  StatusEnum MyStatus =(StatusEnum)Enum.Parse (typeof(StatusEnum),Active,true); 

我倾向于简化:

  public static T ParseEnum< T>(string value)
{
return(T)Enum.Parse(typeof(T),value,true);
}

然后我可以做:

  StatusEnum MyStatus = EnumUtil.ParseEnum< StatusEnum>(Active); 

评论中建议的一个选项是添加一个扩展,这很简单:

  public static T ToEnum< T>(此字符串值)
{
return(T)Enum.Parse (T),value,true);
}

StatusEnum MyStatus =Active.ToEnum< StatusEnum>();

最后,如果无法解析字符串,则可能需要使用默认的枚举: p>

  public static T ToEnum< T>(此字符串值,T defaultValue)
{
if(string。 IsNullOrEmpty(value))
{
return defaultValue;
}

T结果;
return Enum.TryParse< T>(value,true,out result)? result:defaultValue;
}

这使得这个电话:

  StatusEnum MyStatus =Active.ToEnum(StatusEnum.None); 

但是,我会小心的添加一个这样的扩展方法到 string as(没有命名空间控制)它将出现在 string 的所有实例上,无论它们是否持有枚举(所以 1234)。 ToString()。ToEnum(StatusEnum.None)将是有效但无关紧要的)。通常最好避免使用额外的方法来混淆微软的核心课程,这些方法只适用于非常具体的上下文,除非您的整个开发团队对这些扩展功能有很好的了解。


What's the best way to convert a string to an enumeration value in C#?

I have an HTML select tag containing the values of an enumeration. When the page is posted, I want to pick up the value (which will be in the form of a string) and convert it to the enumeration value.

In an ideal world, I could do something like this:

StatusEnum MyStatus = StatusEnum.Parse("Active");

but that isn't a valid code.

解决方案

In .NET Core and .NET >4 there is a generic parse method:

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.

If you have access to C#7 and the latest .NET this is the best way.

Original Answer

In .NET it's rather ugly (until 4 or above):

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

这篇关于如何将字符串转换为C#中的枚举?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆