代码之家  ›  专栏  ›  技术社区  ›  Kelsey

有没有更好的方法来创建泛型转换字符串到枚举方法或枚举扩展?

  •  5
  • Kelsey  · 技术社区  · 15 年前

    我在枚举帮助程序类中有以下方法(为了解决问题,我对其进行了简化):

    static class EnumHelper
    {
        public enum EnumType1 : int
        {
            Unknown = 0,
            Yes = 1,
            No = 2
        }
    
        public enum EnumType2 : int
        {
            Unknown = 0,
            Dog = 1,
            Cat = 2,
            Bird = 3
        }
    
        public enum EnumType3
        {
            Unknown,
            iPhone,
            Andriod,
            WindowsPhone7,
            Palm
        }
    
        public static EnumType1 ConvertToEnumType1(string value)
        {
            return (string.IsNullOrEmpty(value)) ?
                EnumType1.Unknown :
                (EnumType1)(Enum.Parse(typeof(EnumType1), value, true));
        }
    
        public static EnumType2 ConvertToEnumType2(string value)
        {
            return (string.IsNullOrEmpty(value)) ?
                EnumType2.Unknown :
                (EnumType2)(Enum.Parse(typeof(EnumType2), value, true));
        }
    
        public static EnumType3 ConvertToEnumType3(string value)
        {
            return (string.IsNullOrEmpty(value)) ?
                EnumType3.Unknown :
                (EnumType3)(Enum.Parse(typeof(EnumType3), value, true));
        }
    }
    

    所以这里的问题是,我可以把它简化成一个枚举扩展方法,或者是某种可以处理任何类型的单一方法。我发现了一些使用基本枚举的示例,但我的示例中的不同之处在于所有枚举都具有 Unknown 如果字符串为null或空,则需要返回的项(如果找不到匹配项,则希望它失败)。

    可能要找如下的东西:

    EnumType1 value = EnumType1.Convert("Yes");
    // or
    EnumType1 value = EnumHelper.Convert(EnumType1, "Yes");
    

    一个功能来完成所有的任务…如何处理 未知 元素是我被挂断的部分。

    编辑: 已将其中一个枚举调整为不使用整数定义。所以我可以保证永远是0,但是 未知 将始终是正确的文本…我想我可以使用与t(0)相同的示例,但是对文本“unknown”执行另一个解析。

    2 回复  |  直到 15 年前
        1
  •  8
  •   chilltemp    15 年前

    使用这个,假设unknown总是0值。

    public static T ConvertToEnum<T>(this string value) where T : new()
    {
        if( !typeof(T).IsEnum )
            throw new NotSupportedException( "T must be an Enum" );
    
        try
        {
            return (T)Enum.Parse(typeof(T), value);
        }
        catch
        {
            return default(T); // equivalent to (T)0
            //return (T)Enum.Parse(typeof(T), "Unknown"));
        }
    }
    

    用途:

    EnumType2 a = "Cat".ConvertToEnum<EnumType2>(); 
    EnumType2 b = "Person".ConvertToEnum<EnumType2>(); // Unknown
    

    编辑:Op(Kelsey): 你的答案让我找到了正确的答案,所以我想我应该把它包括在这里:

    public static T ConvertTo<T>(this string value)
    {
        T returnValue = (T)(Enum.Parse(typeof(T), "Unknown", true));
        if ((string.IsNullOrEmpty(value) == false) && 
            (typeof(T).IsEnum))
        {
            try { returnValue = (T)(Enum.Parse(typeof(T), value, true)); }
            catch { }
        }
        return returnValue;
    }
    
        2
  •  2
  •   Muad'Dib    15 年前

    使用泛型…像这样的……

    public static TResult ConvertTo<TResult>( this string source )
    {
         if( !typeof(TResult).IsEnum )
         {
             throw new NotSupportedException( "TResult must be an Enum" );
         }
    
        if (!Enum.GetNames(typeof(TResult)).Contains(source))
            return default(TResult);
    
    
         return (TResult)Enum.Parse( typeof(TResult), source );
    }
    

    ( the code came from here )