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

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

在理想的情况下,我可以这样做:

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

但这不是有效的代码。


当前回答

如果你想在null或空时使用默认值(例如,当从配置文件检索时,该值不存在),并在字符串或数字不匹配任何enum值时抛出异常。不过要注意提莫的回答(https://stackoverflow.com/a/34267134/2454604)。

    public static T ParseEnum<T>(this string s, T defaultValue, bool ignoreCase = false) 
        where T : struct, IComparable, IConvertible, IFormattable//If C# >=7.3: struct, System.Enum 
    {
        if ((s?.Length ?? 0) == 0)
        {
            return defaultValue;
        }

        var valid = Enum.TryParse<T>(s, ignoreCase, out T res);

        if (!valid || !Enum.IsDefined(typeof(T), res))
        {
            throw new InvalidOperationException(
                $"'{s}' is not a valid value of enum '{typeof(T).FullName}'!");
        }
        return res;
    }

其他回答

您正在寻找枚举。解析。

SomeEnum enum = (SomeEnum)Enum.Parse(typeof(SomeEnum), "EnumValue");

我们不能假设输入是完全有效的,于是就用了@Keith的答案的变体:

public static TEnum ParseEnum<TEnum>(string value) where TEnum : struct
{
    TEnum tmp; 
    if (!Enum.TryParse<TEnum>(value, true, out tmp))
    {
        tmp = new TEnum();
    }
    return tmp;
}

这里的大多数答案都要求您在每次调用扩展方法时始终传递枚举的默认值。如果你不想采用这种方法,你可以像下面这样实现它:

 public static TEnum ToEnum<TEnum>(this string value) where TEnum : struct
 {
     if (string.IsNullOrWhiteSpace(value))
          return default(TEnum);

     return Enum.TryParse(value, true, out TEnum result) ? result : default(TEnum);

 }

使用默认文字(可从c# 7.1获得)

 public static TEnum ToEnum<TEnum>(this string value, TEnum defaultValue = default) where TEnum : struct
 {
       if (string.IsNullOrWhiteSpace(value))
            return defaultValue ;

       return Enum.TryParse(value, true, out TEnum result) ? result : defaultValue ;

 }

更好的是:

public static TEnum ToEnum<TEnum>(this string value) where TEnum : struct
{
      if (string.IsNullOrWhiteSpace(value))
           return default;

      return Enum.TryParse(value, true, out TEnum result) ? result : default;

}

我使用了class(具有解析和性能改进的Enum强类型版本)。我在GitHub上找到了它,它应该也适用于。net 3.5。它有一些内存开销,因为它缓冲了一个字典。

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

这篇博文是Enums - NET 3.5中更好的语法,更好的性能和TryParse。

和代码: https://github.com/damieng/DamienGKit/blob/master/CSharp/DamienG.Library/System/EnumT.cs

不确定什么时候添加的,但在Enum类上现在有一个

Parse<TEnum>(stringValue)

与问题中的例子一起用:

var MyStatus = Enum.Parse<StatusEnum >(“Active”)

或者忽略大小写:

var MyStatus = Enum.Parse<StatusEnum >(“active”, true)

下面是它使用的反编译方法:

    [NullableContext(0)]
    public static TEnum Parse<TEnum>([Nullable(1)] string value) where TEnum : struct
    {
      return Enum.Parse<TEnum>(value, false);
    }

    [NullableContext(0)]
    public static TEnum Parse<TEnum>([Nullable(1)] string value, bool ignoreCase) where TEnum : struct
    {
      TEnum result;
      Enum.TryParse<TEnum>(value, ignoreCase, true, out result);
      return result;
    }