我想在.NET 4中为我的POCO对象创建一个基类,它将有一个Include(字符串路径)方法,其中路径是“。”。要枚举的继承类的嵌套ICollection属性的分隔导航路径。枚举ICollection <T>使用Reflection的类的属性
例如,给定以下类别;
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
}
}
}
}
}
显然,“无功名单= ...>”行不工作,但你希望得到的要点,并在foreach不会工作,除非是propertyCollection枚举。
所以这是最后一点,即当我直到运行时才知道T的类型时,如何枚举类的ICollection属性?
感谢
是的,它的确如此!我的谢意。 :-) – Phil 2010-09-20 13:21:56