繁体   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