从泛型类中获取ICollection类型的属性列表

本文关键字:属性 列表 类型 ICollection 泛型类 获取 | 更新日期: 2023-09-27 18:15:28

我有一个包含一些ICollection类型属性的对象

基本上这个类是这样的

Class Employee {
public ICollection<Address> Addresses {get;set;}
public ICollection<Performance> Performances {get; set;}
}

问题是通过使用反射在泛型类内部获取ICollection类型的属性名。

My Generic Class is

Class CRUD<TEntity>  {
public object Get() {
 var properties = typeof(TEntity).GetProperties().Where(m=m.GetType() == typeof(ICollection ) ... 
}

但它不工作。

我如何在这里获得属性?

从泛型类中获取ICollection类型的属性列表

GetProperties()返回一个PropertyInfo[]。然后你用m.GetType()做一个Where。如果我们假设你漏掉了一个>,而这是m=>m.GetType(),那么你实际上是在说:

 typeof(PropertyInfo) == typeof(ICollection)

(警告:实际上,它可能是RuntimePropertyInfo等)

的意思是可能是:

typeof(ICollection).IsAssignableFrom(m.PropertyType)
然而

!请注意,ICollection <> ICollection<> <> ICollection<Address>等-所以它甚至不是那么容易。您可能需要:

m.PropertyType.IsGenericType &&
    m.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>)

确认;如此:

static void Main()
{
    Foo<Employee>();
}
static void Foo<TEntity>() {
    var properties = typeof(TEntity).GetProperties().Where(m =>
        m.PropertyType.IsGenericType &&
        m.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>)
    ).ToArray();
    // ^^^ contains Addresses and Performances
}

您可以使用IsGenericType并检查GetGenericTypeDefinitiontypeof(ICollection<>)

public object Get()
{
    var properties =
        typeof (TEntity).GetProperties()
            .Where(m => m.PropertyType.IsGenericType && 
                    m.PropertyType.GetGenericTypeDefinition() == typeof (ICollection<>));
}