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

将Null转换为可为Null的枚举(泛型)

  •  3
  • Richard  · 技术社区  · 14 年前

    我正在编写一些枚举功能,并具有以下功能:

    public static T ConvertStringToEnumValue<T>(string valueToConvert, 
        bool isCaseSensitive)
    {
        if (String.IsNullOrWhiteSpace(valueToConvert))
            return (T)typeof(T).TypeInitializer.Invoke(null);
    
        valueToConvert = valueToConvert.Replace(" ", "");
        if (typeof(T).BaseType.FullName != "System.Enum" &&
            typeof(T).BaseType.FullName != "System.ValueType")
        {
            throw new ArgumentException("Type must be of Enum and not " +
                typeof (T).BaseType.FullName);
        }
    
        if (typeof(T).BaseType.FullName == "System.ValueType")
        {
            return (T)Enum.Parse(Nullable.GetUnderlyingType(typeof(T)),
                valueToConvert, !isCaseSensitive);
        }
    
        return (T)Enum.Parse(typeof(T), valueToConvert, !isCaseSensitive);
    }
    

    EnumHelper.ConvertStringToEnumValue<Enums.Animals?>("Cat");
    

    这和预期的一样。但是,如果我运行以下命令:

    EnumHelper.ConvertStringToEnumValue<Enums.Animals?>(null);
    

    有人知道怎么解决这个问题吗?

    3 回复  |  直到 14 年前
        1
  •  9
  •   Preet Sangha    14 年前

    尝试

    if (String.IsNullOrWhiteSpace(valueToConvert))
                  return default(T);
    
        2
  •  0
  •   diegodsp    8 年前

    我有不同的方法,使用扩展和泛型。

    public static T ToEnum<T>(this string s) {
        if (string.IsNullOrWhiteSpace(s))
            return default(T);
    
        s = s.Replace(" ", "");
        if (typeof(T).BaseType.FullName != "System.Enum" &&
            typeof(T).BaseType.FullName != "System.ValueType") {
            throw new ArgumentException("Type must be of Enum and not " + typeof(T).BaseType.FullName);
        }
    
        if (typeof(T).BaseType.FullName == "System.ValueType")
            return (T)Enum.Parse(Nullable.GetUnderlyingType(typeof(T)), s, true);
    
        return (T)Enum.Parse(typeof(T), s, true);
    }
    

    Gender? g = "Female".ToEnum<Gender?>();
    
        3
  •  0
  •   Pangamma    7 年前

    这个完成了任务,看起来也很漂亮。希望有帮助!

        /// <summary>
        /// <para>More convenient than using T.TryParse(string, out T). 
        /// Works with primitive types, structs, and enums.
        /// Tries to parse the string to an instance of the type specified.
        /// If the input cannot be parsed, null will be returned.
        /// </para>
        /// <para>
        /// If the value of the caller is null, null will be returned.
        /// So if you have "string s = null;" and then you try "s.ToNullable...",
        /// null will be returned. No null exception will be thrown. 
        /// </para>
        /// <author>Contributed by Taylor Love (Pangamma)</author>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="p_self"></param>
        /// <returns></returns>
        public static T? ToNullable<T>(this string p_self) where T : struct
        {
            if (!string.IsNullOrEmpty(p_self))
            {
                var converter = System.ComponentModel.TypeDescriptor.GetConverter(typeof(T));
                if (converter.IsValid(p_self)) return (T)converter.ConvertFromString(p_self);
                if (typeof(T).IsEnum) { T t; if (Enum.TryParse<T>(p_self, out t)) return t;}
            }
    
            return null;
        }
    

    https://github.com/Pangamma/PangammaUtilities-CSharp/tree/master/src/StringExtensions