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

本文关键字:属性 类型 基类 实现 泛型 获取 | 更新日期: 2023-09-27 18:36:35

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

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

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

您直接查询属性的类型,这意味着它本身必须是特定类型 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
;
我一直

在使用以下代码,它运行良好。

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

我有一个定义为:

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