2009-10-15 7 views

答えて

8

GetGenericTypeDefinitiontypeof(Collection<>)は仕事を行います。

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

あなたは 'ICollectionを'ではなく 'コレクション'のようなものに対してテストではないでしょうか?一般的なコレクションの多く(例えば 'List ')は 'Collection 'から継承しません。 – LukeH

+2

'p.GetType()'は、プロパティの型の代わりに 'RuntimePropertyInfo'を記述する' Type'を返します。また、 'GetGenericTypeDefinition()'は非ジェネリック型の例外をスローします。 –

+1

正確には、GetGenericTypeDefinitionは非ジェネリック型の例外をスローします。 – 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<>"); 
    } 
} 

あなたはタイプがジェネリックでない場合、そうでないGetGenericTypeDefinition()は例外がスローされます、テストt.IsGenericTypex.IsGenericTypeを必要としています。

ICollection<T>と宣言された場合、tColl.IsAssignableFrom(t.GetGenericTypeDefinition())trueを返します。プロパティはICollection<T>を実装型として宣言されている場合

そして t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl)trueを返します。

たとえば、tColl.IsAssignableFrom(t.GetGenericTypeDefinition())は、List<int>の場合はfalseを返します。 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; } 
} 

出力用


私がテストしたすべてのこれらの組み合わせは:

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<> 
関連する問題