2012-03-19 7 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 पर संपत्ति को हटा देता हूं तो कोड काम करता है।

प्रतिबिंब के माध्यम से टाइपऑफ enum को जानने के बिना मैं कोड को कैसे काम कर सकता हूं?

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

गोल्डन! बहुत बहुत धन्यवाद –

+0

मुझे पता है कि यह 2012 से है, लेकिन किसी भी व्यक्ति के लिए जो एक ही समस्या (जैसे मेरे) पर ठोकर खा रहा है - एक छोटा सुधार: टी.जीटजेनेरिक टाइप टाइप() == ... से पहले टी.इसेजेनेरिक टाइप के लिए एक चेक जोड़ें कोड एक गैर-शून्यणीय enum प्रकार के लिए तोड़ सकता है –

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

संबंधित मुद्दे