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
我正在嘗試與另一個反射,但我不能得到它.. –