2017-10-20 102 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); 
}