2012-03-19 16 views
8

文字列を解析して、MyEnum型のnull可能なプロパティに戻そうとしています。Nullable Enumを解析する

public MyEnum? MyEnumProperty { get; set; } 

私はライン上のエラーを取得しています:

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

私は以下のサンプルのコンソールのテストを持っています。 MyEntity.MyEnumPropertyプロパティでnullableを削除すると、コードが機能します。

リフレクション以外で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

ゴールデン!ありがとうございました –

+0

私はこれが2012年のものだと知っていますが、同じ問題(私のような)に遭遇した人のために - 小さな改善:t.GetGenericTypeDefinition()== ...の前にt.IsGenericTypeのチェックを追加します。コードはnull値ではない列挙型に対して壊れることがあります –

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

関連する問題