2013-02-16 4 views
10

getプロパティの型にリフレクションを使用します。 これは、このコードpropertyInfo.PropertyType.Name私のコードNullable型からのリフレクションでPropertyType.Nameを取得

var properties = type.GetProperties(); 
foreach (var propertyInfo in properties) 
{ 
    model.ModelProperties.Add(
           new KeyValuePair<Type, string> 
               (propertyInfo.PropertyType.Name, 
               propertyInfo.Name) 
          ); 
} 

では大丈夫ですが、私の財産の種類がNullableであれば、私はこのNullable'1文字列を取得し、このstirng System.Nullable1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

+0

をそれがNULL可能ですか? –

+0

そして、それはあなたが得たい文字列ですか?これは、タイプのジェネリックパラメータにアクセスできるPropertyTypeのプロパティ/メソッドを使用する必要があるようです。 –

+2

http://stackoverflow.com/questions/5174423/getting-basic-datatype-rather-than-weird-nullable-one-via-reflection-in-c-sha – TheNextman

答えて

22

がNULL可能タイプを探すために、あなたのコードを変更して取得する場合FullNameを記述する場合その場合、PropertyTypeを最初の一般的なアグリーメントとして使用してください:

var propertyType = propertyInfo.PropertyType; 

if (propertyType.IsGenericType && 
     propertyType.GetGenericTypeDefinition() == typeof(Nullable<>)) 
    { 
     propertyType = propertyType.GetGenericArguments()[0]; 
    } 

model.ModelProperties.Add(new KeyValuePair<Type, string> 
         (propertyType.Name,propertyInfo.Name)); 
8

これは古い質問ですが、これも同様に実行されました。私は@ Igoyの答えが好きですが、型がnull可能な型の配列であれば動作しません。これは、nullable/genericとarrayの組み合わせを処理するための拡張メソッドです。うまくいけば、同じ質問をしている人には役に立ちます。このように複雑よう

public static string GetDisplayName(this Type t) 
{ 
    if(t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>)) 
     return string.Format("{0}?", GetDisplayName(t.GetGenericArguments()[0])); 
    if(t.IsGenericType) 
     return string.Format("{0}<{1}>", 
          t.Name.Remove(t.Name.IndexOf('`')), 
          string.Join(",",t.GetGenericArguments().Select(at => at.GetDisplayName()))); 
    if(t.IsArray) 
     return string.Format("{0}[{1}]", 
          GetDisplayName(t.GetElementType()), 
          new string(',', t.GetArrayRank()-1)); 
    return t.Name; 
} 

これはケースを処理します:

typeof(Dictionary<int[,,],bool?[][]>).GetDisplayName() 

戻り値:

Dictionary<Int32[,,],Boolean?[][]> 
関連する問題