Get List if Properties of type ICollection from Generic Class

六月ゝ 毕业季﹏ 提交于 2019-12-22 08:36:56

问题


I have an object that contains some ICollection type properties

So basically the class looks like this:

Class Employee {

public ICollection<Address> Addresses {get;set;}

public ICollection<Performance> Performances {get; set;}

}

The problem is get property names of type ICollection, inside of Generic class, by using reflection.

My Generic Class is

Class CRUD<TEntity>  {

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

But it is not working.

How can I get a property here?


回答1:


GetProperties() returns a PropertyInfo[]. You then do a Where using m.GetType(). If we assume that you missed a >, and this is m=>m.GetType(), then you are actually saying:

 typeof(PropertyInfo) == typeof(ICollection)

(caveat: actually, it is probably a RuntimePropertyInfo, etc)

What you mean is probably:

typeof(ICollection).IsAssignableFrom(m.PropertyType)

However! Note that ICollection <> ICollection<> <> ICollection<Address> etc - so it isn't even that easy. You might need:

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

Confirmed; this works:

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
}



回答2:


You can use IsGenericType and check GetGenericTypeDefinition against typeof(ICollection<>)

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


来源:https://stackoverflow.com/questions/25032583/get-list-if-properties-of-type-icollection-from-generic-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!