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

반사 속도가 느린을, 컴파일 타임에 Type을 모르는 경우 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); 
} 
관련 문제