Entity Framework生成的DynamicProxies是您的POCO类的后代。
foreach (var item in items)
{
YourNamespace.Site site = (YourNamespace.Site)item.GetType().GetProperty("Site").GetValue(item,null);
Console.WriteLine(site.SiteName);
}
如果你需要使用反射由于某种原因,这也是可能的:那就是,如果你上溯造型的结果POCO你实际上可以访问所有属性
foreach (var item in items)
{
PropertyInfo piSite = item.GetType().GetProperty("Site");
object site = piSite.GetValue(item,null);
PropertyInfo piSiteName = site.GetType().GetProperty("SiteName");
object siteName = piSiteName.GetValue(site, null);
Console.WriteLine(siteName);
}
反思是缓慢的,所以我会使用TypeDescriptor,如果我不知道编译时Type:
PropertyDescriptor siteProperty = null;
PropertyDescriptor siteNameProperty = null;
foreach (var item in items)
{
if (siteProperty == null) {
PropertyDescriptorCollection itemProperties = TypeDescriptor.GetProperties(item);
siteProperty = itemProperties["Site"];
}
object site = siteProperty.GetValue(item);
if (siteNameProperty == null) {
PropertyDescriptorCollection siteProperties = TypeDescriptor.GetProperties(site);
siteNameProperty = siteProperties["SiteName"];
}
object siteName = siteNameProperty.GetValue(site);
Console.WriteLine(siteName);
}
为什么'null'参数?不会[GetValue(object o)](https://msdn.microsoft.com/en-us/library/hh194385(v = vs.110).aspx)过载会更好吗? – orhtej2
至于获取值:你可以对返回的对象进行另一次反射调用,或者只使用['dynamic' type](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic)为你完成这项工作。 – orhtej2
我正在尝试与另一个反射,但我不能得到它.. –