2009-10-15 14 views

risposta

8

GetGenericTypeDefinition e typeof(Collection<>) farà il lavoro:

if(p.PropertyType.IsGenericType && typeof(Collection<>).IsAssignableFrom(p.PropertyType.GetGenericTypeDefinition()) 
+3

non si dovrebbe confrontare con qualcosa del tipo '' ICollection piuttosto che '' Collection ? Molte delle raccolte generiche (ad esempio, 'Lista ') non ereditano da 'Raccolta '. – LukeH

+2

'p.GetType()' restituirà un 'Tipo' che descrive' RuntimePropertyInfo' invece del tipo della proprietà. Anche 'GetGenericTypeDefinition()' genera un'eccezione per tipi non generici. –

+1

Esattamente, GetGenericTypeDefinition genera un'eccezione per tipi non generici. – Shaggydog

31
Type tColl = typeof(ICollection<>); 
foreach (PropertyInfo p in (o.GetType()).GetProperties()) { 
    Type t = p.PropertyType; 
    if (t.IsGenericType && tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) || 
     t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl)) { 
     Console.WriteLine(p.Name + " IS an ICollection<>"); 
    } else { 
     Console.WriteLine(p.Name + " is NOT an ICollection<>"); 
    } 
} 

è necessario il test t.IsGenericType e x.IsGenericType, altrimenti GetGenericTypeDefinition() un'eccezione se il tipo non è generica.

Se la proprietà viene dichiarata come ICollection<T>, il numero tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) restituirà true.

Se la proprietà è dichiarato come un tipo che implementa ICollection<T> poi t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl) tornerà true.

Si noti che tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) restituisce false per un List<int> per esempio.


ho testato tutte queste combinazioni per MyT o = new MyT();

private interface IMyCollInterface1 : ICollection<int> { } 
private interface IMyCollInterface2<T> : ICollection<T> { } 
private class MyCollType1 : IMyCollInterface1 { ... } 
private class MyCollType2 : IMyCollInterface2<int> { ... } 
private class MyCollType3<T> : IMyCollInterface2<T> { ... } 

private class MyT 
{ 
    public ICollection<int> IntCollection { get; set; } 
    public List<int> IntList { get; set; } 
    public IMyCollInterface1 iColl1 { get; set; } 
    public IMyCollInterface2<int> iColl2 { get; set; } 
    public MyCollType1 Coll1 { get; set; } 
    public MyCollType2 Coll2 { get; set; } 
    public MyCollType3<int> Coll3 { get; set; } 
    public string StringProp { get; set; } 
} 

uscita:

IntCollection IS an ICollection<> 
IntList IS an ICollection<> 
iColl1 IS an ICollection<> 
iColl2 IS an ICollection<> 
Coll1 IS an ICollection<> 
Coll2 IS an ICollection<> 
Coll3 IS an ICollection<> 
StringProp is NOT an ICollection<> 
Problemi correlati