获取实现特定通用基类型的所有属性

时间:2015-01-07 22:48:01

标签: c# generics reflection

我有一个对象具有不同类型的泛型集合属性,如下所示:

ObservableCollection<T>, BindingList<T>

我想返回实现ICollection<>的所有属性。我试过这个没有成功。看来这个使用反射的查询并没有检查实现的接口:

IEnumerable<PropertyInfo> childCollections =
    typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance)
        .Where(p => p.PropertyType.IsGenericType
               && p.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>))
        .Select(g => g);

2 个答案:

答案 0 :(得分:0)

我一直在使用以下代码,它运行得很好。

var properties = typeof(T).GetProperties().Where(m =>
                    m.PropertyType.IsGenericType &&
                    m.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>));

我有一个类集合定义为:

public virtual ICollection<Transaction> Transactions
        {
            get;
            set;
        }

答案 1 :(得分:0)

您正在直接查询属性的类型,这意味着它本身必须是特定类型ICollection<>。要检查实现接口,您需要.GetInterfaces()

IEnumerable<PropertyInfo> childCollections =
  from p in typeof(T).GetProperties()
  where p.PropertyType.GetInterfaces().Any(i =>
    i.IsGenericType && 
    i.GetGenericTypeDefinition() == typeof(ICollection<>)
  )
  select p
;