2013-02-16 15 views
10

Voglio usare reflection per ottenere il tipo di proprietà. questo è il mio codiceOttieni PropertyType.Name in reflection da tipo Nullable

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

questo codice propertyInfo.PropertyType.Name è ok, ma se il mio tipo di proprietà è Nullable ottengo questa stringa Nullable'1 e se scrivere FullName se ottenere questo stirng System.Nullable1[[System.DateTime, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]

+0

E 'un Nullable ? –

+0

E qual è la stringa che vuoi ottenere? Sembra che dovrai usare le proprietà/i metodi su PropertyType che ti consente di accedere ai parametri generici del tipo. –

+2

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

risposta

22

modificare il codice per cercare tipo nullable , in tal caso, prendi PropertyType come primo agrume generico:

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

Questa è una domanda vecchia, ma mi sono imbattuto anche in questo. Mi piace la risposta di @ Igoy, ma non funziona se il tipo è un array di un tipo nullable. Questo è il mio metodo di estensione per gestire qualsiasi combinazione di nullable/generico e array. Spero che sarà utile a qualcuno con la stessa domanda.

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

Questo consente di gestire i casi di così complicato come questo:

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

Returns:

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