2009-10-15 41 views

Trả lời

8

GetGenericTypeDefinitiontypeof(Collection<>) sẽ thực hiện công việc:

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

nên không kiểm tra đối với một cái gì đó như 'ICollection 'chứ không phải' Bộ sưu tập '? Nhiều bộ sưu tập chung (ví dụ: 'Danh sách ') không được kế thừa từ 'Bộ sưu tập '. – LukeH

+2

'p.GetType()' sẽ trả về một 'Loại' mô tả' RuntimePropertyInfo' thay vì loại thuộc tính. Ngoài ra 'GetGenericTypeDefinition()' ném một ngoại lệ cho các loại không chung chung. –

+1

Chính xác, GetGenericTypeDefinition ném ngoại lệ cho các loại không chung chung. – 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<>"); 
    } 
} 

Bạn cần kiểm tra t.IsGenericTypex.IsGenericType, nếu không GetGenericTypeDefinition() sẽ ném một ngoại lệ nếu loại là không chung chung.

Nếu thuộc tính được khai báo là ICollection<T> thì tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) sẽ trả lại true.

Nếu thuộc tính được khai báo là loại thực hiện ICollection<T> thì t.GetInterfaces().Any(x => x.IsGenericType && x.GetGenericTypeDefinition() == tColl) sẽ trả về true.

Lưu ý rằng tColl.IsAssignableFrom(t.GetGenericTypeDefinition()) trả lại false cho ví dụ List<int>.


Tôi đã thử nghiệm tất cả những kết hợp này cho 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; } 
} 

Output:

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<> 
Các vấn đề liên quan