Get List if Properties of type ICollection from Generic Class

大兔子大兔子 提交于 2019-12-05 12:20:34

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
}

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