Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
450 views
in Technique[技术] by (71.8m points)

c# - 在C#中将字符串转换为枚举(Convert a string to an enum in C#)

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

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

I have an HTML select tag containing the values of an enumeration.

(我有一个HTML选择标签,其中包含枚举的值。)

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.

(但这不是有效的代码。)

  ask by Ben Mills translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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的核心类混乱,除非整个开发团队对这些扩展的工作有很好的了解。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...