2017-10-20 14 views
0

リフレクションを使用してプロパティを取得していますが、GetValue(item,null)がオブジェクトを返すときに問題が発生しています。 私がやった:リフレクションを使用したプロパティの取得

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

はそれを行う、私はオブジェクトSystem.Data.Entity.DynamicProxies.Siteを得ました。デバッグすると、そのオブジェクトのすべてのプロパティが表示されますが、取得できません。たとえば、1つのプロパティはsiteNameですが、どうすればその価値を得ることができますか?

+0

なぜヌルパラメータですか? [GetValue(object o)](https://msdn.microsoft.com/en-us/library/hh194385(v=vs.110).aspx)のオーバーロードは改善されませんか? – orhtej2

+0

値を取得する方法:返されたオブジェクトに対して別のリフレクションコールを行うか、['dynamic'型]を使用します(https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/types)。/use-type-dynamic)を使用してジョブを実行します。 – orhtej2

+0

私は別の反射を試していますが、私はそれを得ることはできません.. –

答えて

0

Entity Frameworkによって生成されるDynamicProxiesは、POCOクラスの子孫です。それはあなたがPOCOに結果をアップキャスト場合は、実際にすべてのプロパティにアクセスすることができ、次のとおりです。

foreach (var item in items) 
{ 
    YourNamespace.Site site = (YourNamespace.Site)item.GetType().GetProperty("Site").GetValue(item,null); 
    Console.WriteLine(site.SiteName); 
} 

あなたには、いくつかの理由のためにリフレクションを使用する必要がある場合は、これもまた可能である:

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を使用します:

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); 
} 
関連する問題