获取ICollection <baseentity> </baseentity>类型的属性

时间:2014-08-21 10:33:49

标签: c# generics reflection

我正在努力获得类ICollection<BaseEntity>的所有属性。

示例实体:

public class BaseEntity
{
    public int Id { get; set; }
}

public class Post : BaseEntity
{
    public string Name { get; set; }
}

public class User : BaseEntity
{
    public string Name { get; set; }
    public ICollection<Post> Posts { get; set; }
    public Post MyPost { get; set; }
}

我可以使用以下命令获取从BaseEntity派生的类的属性:

var baseEntProps = properties.Where(p => typeof(BaseEntity).IsAssignableFrom(p.PropertyType));

我如何为ICollection做同样的事情?我试过了

var p2 = properties.Where(p => typeof (ICollection<BaseEntity>).IsAssignableFrom(p.PropertyType));

但这并没有给出任何结果。我可以使用ICollection<Post>的{​​{1}} instad,但这会影响我想要做的目的。

ICollection<BaseEntity>

1 个答案:

答案 0 :(得分:4)

这很难看,但可以这样做:

var baseEntProps = properties
.Where(p => p.PropertyType.IsGenericType &&
            p.PropertyType.GetGenericTypeDefinition() == typeof(ICollection<>) &&
            typeof(BaseEntity).IsAssignableFrom(p.PropertyType.GetGenericArguments()[0]));