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

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

问题描述

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

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

我有一个包含枚举值的 HTML 选择标记.当页面发布时,我想取值(将以字符串的形式)并将其转换为相应的枚举值.

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

但这不是一个有效的代码.

but that isn't a valid code.

推荐答案

在 .NET Core 和 .NET Framework ≥4.0 有一个通用的解析方法:

In .NET Core and .NET Framework ≥4.0 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);

我倾向于将其简化为:

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