簡體   English   中英

枚舉ICollection <T> 使用反射的類的屬性

[英]Enumerate ICollection<T> property of class using Reflection

我正在嘗試為.NET 4中的POCO對象創建基類,該基類將具有Include(string path)方法,其中path是“。”。 要枚舉的繼承類的嵌套ICollection屬性的定界導航路徑。

例如,給定以下類;

public class Region
{
    public string Name { get; set; }
    public ICollection<Country> Countries { get; set; }
}
public partial class Region : EntityBase<Region> {}

public class Country
{
    public string Name { get; set; }
    public ICollection<City> Cities { get; set; }
}
public partial class Country : EntityBase<Country> {}

public class City
{
    public string Name { get; set; }
}
public partial class City : EntityBase<City> {}

我希望能夠做這樣的事情;

Region region = DAL.GetRegion(4);
region.Include("Countries.Cities");

到目前為止,我有以下內容;

public class EntityBase<T> where T : class 
{
    public void Include(string path)
    {
        // various validation has been omitted for brevity
        string[] paths = path.Split('.');
        int pathLength = paths.Length;
        PropertyInfo propertyInfo = type(T).GetProperty(paths[0]);
        object propertyValue = propertyInfo.GetValue(this, null);
        if (propertyValue != null)
        {
            Type interfaceType = propertyInfo.PropertyType;
            Type entityType = interfaceType.GetGenericArguments()[0];

            // I want to do something like....
            var propertyCollection = (ICollection<entityType>)propertyValue;
            foreach(object item in propertyCollection)
           {
               if (pathLength > 1)
               {
                   // call Include method of item for nested path
               }
           }
        }
    }
}

顯然,“ var list = ...>”行不起作用,但希望您能理解要點,除非propertyCollection可枚舉,否則foreach不會起作用。

所以這是最后一點,即當我直到運行時才知道T的類型時,如何枚舉類的ICollection屬性?

謝謝

您不需要為此進行反思。 為了枚舉它,您只需要一個IEnumerable ICollection<T>繼承IEnumerable ,因此您的所有集合都是可枚舉的。 因此,

var propertyCollection = (IEnumerable) propertyValue;
foreach (object item in propertyCollection)
    // ...

將工作。

當客戶端可以在編譯時解析泛型類型時,通常使用泛型。 撇開這一點,由於您所需要做的就是枚舉propertyCollection (將序列的每個元素都簡單地作為System.Object查看),因此您需要做的是:

var propertyCollection = (IEnumerable)propertyValue;
foreach(object item in propertyCollection)
{
    ...
}    

這是絕對安全的,因為ICollection<T>擴展了IEnumerable<T> ,而后者又擴展了IEnumerable T實際上最終在運行時結束時是無關緊要的,因為循環僅需要object

真正的問題是: System.Object是否足以在循環內滿足您的目的?

暫無
暫無

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

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