在C#中将字符串转换为枚举 [英] Convert a string to an enum in C#

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

问题描述

在C#中将字符串转换为枚举值的最佳方法是什么?

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

我有一个包含枚举值的HTML select标记。发布页面后,我要提取值(将以字符串形式)并将其转换为相应的枚举值。

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 corresponding enumeration value.

在理想的世界中,我可以做这样的事情:

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

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

但这不是有效的代码。

推荐答案

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

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

Enum.TryParse("Active", out StatusEnum myStatus);

这还包括C#7的新内联 out 变量,这样就可以进行尝试解析,转换为显式枚举类型并初始化+填充 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和最新的.NET,这是最好的方法。

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

在.NET中,它非常难看(直到4个或以上):

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);
}

然后我可以做:

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;
}

此呼叫为:

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

但是,我会小心地在 string ,因为(没有名称空间控制)它会出现在 string 的所有实例中,无论它们是否包含枚举(因此 1234。 ToString()。ToEnum(StatusEnum.None)是有效的,但没有意义。通常最好避免使用仅适用于非常特定的上下文的额外方法来使Microsoft的核心类混乱,除非整个开发团队对这些扩展的用途有很好的了解。

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天全站免登陆