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

查看:112
本文介绍了如何将字符串转换为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 enumeration value.

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

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

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

但不是有效的code。

but that isn't valid code.

推荐答案

这是相当难看:

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

不过,我会小心添加像这样的扩展方法字符串如(无命名空间的控制),它会出现在的所有实例的字符串是否持有一个枚举或没有(那么 1234.ToString()。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天全站免登陆