2010-09-28 48 views
3

我寫了一些枚舉功能,並有以下幾點:空轉換可空枚舉(通用)

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); 

它打破了TypeInitializer爲空的錯誤。

有誰知道如何解決這個問題?

謝謝大家!

+1

究竟爲什麼你調用類型初始化?在我9年的C#中,我從來沒有**需要這樣做! – leppie 2010-09-28 08:37:09

+0

實際上,這個類型初始化器甚至不會返回任何東西。代碼是假的,對不起。 – leppie 2010-09-28 08:38:33

+1

@leppie,因此我發佈了這個問題。我正在尋找一種方法來做到這一點,顯然TypeInitializer不是這樣做的正確方法。以下來自Preet的回答是我正在尋找的。 – Richard 2010-09-28 08:51:47

回答

9

嘗試

if (String.IsNullOrWhiteSpace(valueToConvert)) 
       return default(T); 
0

我有一個不同的方法,通過延伸和仿製藥。

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?>(); 
0

這一次能夠完成任務,它也看起來很漂亮。希望能幫助到你!

/// <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