2013-02-16 11 views
10

Chcę użyć refleksji, aby uzyskać typ właściwości. to jest mój kodPobierz PropertyType.Name w odbiciu od Nullable typu

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

ten kod propertyInfo.PropertyType.Name jest ok, ale jeśli mój typ nieruchomość jest Nullable ja dostać ten Nullable'1 ciąg i jeśli napisać FullName jeśli dostać ten stirng System.Nullable1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

+0

jest to Nullable ? –

+0

A który ciąg znaków chcesz otrzymać? Wygląda na to, że będziesz musiał użyć właściwości/metod w PropertyType, który umożliwia dostęp do ogólnych parametrów typu. –

+2

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

Odpowiedz

22

Zmień swój kod w poszukiwaniu wartości pustych typu w tym przypadku wziąć PropertyType jako pierwszy generycznego agruement:

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

to stara sprawa, ale wpadłem na to jak dobrze. Lubię odpowiedź @ Igoya, ale nie działa, jeśli typ jest tablicą typu zerowego. Jest to moja metoda rozszerzenia do obsługi dowolnej kombinacji wartości nullable/generic i array. Mam nadzieję, że przyda się to komuś z tym samym pytaniem.

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

To zajmie przypadki tak skomplikowane jak to:

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

Powroty:

Dictionary<Int32[,,],Boolean?[][]>