2012-03-19 103 views
8

我想解析一個字符串回MyEnum類型的可空屬性。解析爲可空枚舉

public MyEnum? MyEnumProperty { get; set; } 

我在網上收到一個錯誤:

Enum result = Enum.Parse(t, "One") as Enum; 
// Type provided must be an Enum. Parameter name: enumType 

下面我有一個樣本測試控制檯。如果我在屬性MyEntity.MyEnumProperty上刪除空值,代碼將起作用。

我怎樣才能得到的代碼工作,而不知道typeof枚舉,除了通過反射?

static void Main(string[] args) 
    { 
     MyEntity e = new MyEntity(); 
     Type type = e.GetType(); 
     PropertyInfo myEnumPropertyInfo = type.GetProperty("MyEnumProperty"); 

     Type t = myEnumPropertyInfo.PropertyType; 
     Enum result = Enum.Parse(t, "One") as Enum; 

     Console.WriteLine("result != null : {0}", result != null); 
     Console.ReadKey(); 
    } 

    public class MyEntity 
    { 
     public MyEnum? MyEnumProperty { get; set; } 
    } 

    public enum MyEnum 
    { 
     One, 
     Two 
    } 
} 

回答

14

增加對Nullable<T>一種特殊情況將工作:

Type t = myEnumPropertyInfo.PropertyType; 
if (t.GetGenericTypeDefinition() == typeof(Nullable<>)) 
{ 
    t = t.GetGenericArguments().First(); 
} 
+1

金!非常感謝你 – 2012-03-19 02:06:28

+0

我知道這是從2012年開始的,但對於任何偶然發現同樣問題的人(如我) - 小改進:在t.GetGenericTypeDefinition()== ...之前添加t.IsGenericType的檢查,否則該代碼可能會因爲不可空的枚舉類型而中斷 – 2016-06-24 10:07:50

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