簡體   English   中英

從Generic Class獲取ICollection類型的屬性的列表

[英]Get List if Properties of type ICollection from Generic Class

我有一個包含一些ICollection類型屬性的對象

所以基本上這個類看起來像這樣:

Class Employee {

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

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

}

問題是通過使用反射獲取Generic類內部的ICollection類型的屬性名稱。

我的通用類是

Class CRUD<TEntity>  {

public object Get() {
 var properties = typeof(TEntity).GetProperties().Where(m=m.GetType() == typeof(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並針對typeof(ICollection<>)檢查GetGenericTypeDefinition typeof(ICollection<>)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM