How should I convert a string to an enum in C#?

2018-12-31 02:25发布

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.

标签: c# string enums
20条回答
几人难应
2楼-- · 2018-12-31 02:55
object Enum.Parse(System.Type enumType, string value, bool ignoreCase);

So if you had an enum named mood it would look like this:

   enum Mood
   {
      Angry,
      Happy,
      Sad
   } 

   // ...
   Mood m = (Mood) Enum.Parse(typeof(Mood), "Happy", true);
   Console.WriteLine("My mood is: {0}", m.ToString());
查看更多
栀子花@的思念
3楼-- · 2018-12-31 02:55

You can extend the accepted answer with a default value to avoid exceptions:

public static T ParseEnum<T>(string value, T defaultValue) where T : struct
{
    try
    {
        T enumValue;
        if (!Enum.TryParse(value, true, out enumValue))
        {
            return defaultValue;
        }
        return enumValue;
    }
    catch (Exception)
    {
        return defaultValue;
    }
}

Then you call it like:

StatusEnum MyStatus = EnumUtil.ParseEnum("Active", StatusEnum.None);
查看更多
高级女魔头
4楼-- · 2018-12-31 02:55
// str.ToEnum<EnumType>()
T static ToEnum<T>(this string str) 
{ 
    return (T) Enum.Parse(typeof(T), str);
}
查看更多
浅入江南
5楼-- · 2018-12-31 02:56

Use Enum.TryParse<T>(String, T) (≥ .NET 4.0):

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

It can be simplified even further with C# 7.0's parameter type inlining:

Enum.TryParse("Active", out StatusEnum myStatus);
查看更多
宁负流年不负卿
6楼-- · 2018-12-31 02:57

I used class (strongly-typed version of Enum with parsing and performance improvements). I found it on GitHub, and it should work for .NET 3.5 too. It has some memory overhead since it buffers a dictionary.

StatusEnum MyStatus = Enum<StatusEnum>.Parse("Active");

The blogpost is Enums – Better syntax, improved performance and TryParse in NET 3.5.

And code: https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/System/EnumT.cs

查看更多
墨雨无痕
7楼-- · 2018-12-31 03:00

Enum.Parse is your friend:

StatusEnum MyStatus = (StatusEnum)Enum.Parse(typeof(StatusEnum), "Active");
查看更多
登录 后发表回答