2017-10-20 101 views
0

我使用反射获取某些属性,并且在GetValue(item,null)返回对象时遇到问题。 我所做的:使用反射获取属性

foreach (var item in items) 
{ 
    item.GetType().GetProperty("Site").GetValue(item,null) 
} 

这样做,我得到了一个对象System.Data.Entity.DynamicProxies.Site。调试它,我可以看到该对象的所有属性,但我无法得到它。例如,一个属性是:siteName,我怎样才能得到它的价值?

+0

为什么'null'参数?不会[GetValue(object o)](https://msdn.microsoft.com/en-us/library/hh194385(v = vs.110).aspx)过载会更好吗? – orhtej2

+0

至于获取值:你可以对返回的对象进行另一次反射调用,或者只使用['dynamic' type](https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types/using-type-dynamic)为你完成这项工作。 – orhtej2

+0

我正在尝试与另一个反射,但我不能得到它.. –

回答

0

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); 
}