获得普通类类型的ICollection的名单,如果属性 [英] Get List if Properties of type ICollection from Generic Class

查看:280
本文介绍了获得普通类类型的ICollection的名单,如果属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

}

问题是得到类型的ICollection的属性名称,泛型类的内部,通过使用反射。

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

我的泛型类是

Class CRUD<TEntity>  {

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

但它不工作。

我怎么能到这里的属性?

How can I get a property here?

推荐答案

的GetProperties()返回的PropertyInfo [] 。然后你做了其中,使用 m.GetType ()如果我们假设你错过了一个> ,这是 M => m.GetType( ),那么你实际上是在说:

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)

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

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

您的的意思是的大概是:

typeof(ICollection).IsAssignableFrom(m.PropertyType)

不过!请注意, 的ICollection <> 的ICollection<> <> 的ICollection<地址> 等 - 因此它甚至不是那么容易。您可能需要:

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
}

这篇关于获得普通类类型的ICollection的名单,如果属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆