繁体   English   中英

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

[英]Get all properties which implements a specific generic base type

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

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

我一直在使用以下代码,并且运行良好。

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

我有一个类集合定义为:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM