2013-07-03 2 views
7

필드를 찾고있는 동적 개체의 속성을 반복하고 있습니다 (던지기 전에 존재 여부를 안전하게 평가하는 방법을 알 수 없다) 예외. 당신의 도움이동적 개체에 필드가 있는지 여부를 안전하게 확인하는 방법

건배

 foreach (dynamic item in routes_list["mychoices"]) 
     { 
      // these fields may or may not exist 
      int strProductId = item["selectedProductId"]; 
      string strProductId = item["selectedProductCode"]; 
     } 

감사합니다!

+0

[어떻게하면 동적 테스트하는의 중복 가능성 속성을 사용할 수 있습니다] (http://stackoverflow.com/questions/2998954/dynamic-how-to-test-if-a-property-is-available) –

+0

왜 foreach (동적 항목 개미 그냥 사용하려고 var –

+0

이것은 가장 좋은 대답입니다 http://stackoverflow.com/questions/2839598/how-to-detect-if-a-property-exists-on-a-dynamic-object-in-c – Ehsan

답변

1

다이내믹 변수를 try catch로 둘러 쌀 필요가 있습니다. 안전한 방법은 더 좋은 방법은 없습니다.

try 
{ 
    dynamic testData = ReturnDynamic(); 
    var name = testData.Name; 
    // do more stuff 
} 
catch (RuntimeBinderException) 
{ 
    // MyProperty doesn't exist 
} 
+0

가장 쉬운 방법은 생각합니다. – MikeW

0

이것은 간단 할 것입니다. 값이 널 (null) 또는 비어 있는지 점검하는 조건을 설정하십시오. 값이 있으면 해당 값을 해당 데이터 유형에 지정하십시오.

foreach (dynamic item in routes_list["mychoices"]) 
     { 
      // these fields may or may not exist 

      if (item["selectedProductId"] != "") 
      { 
       int strProductId = item["selectedProductId"]; 
      } 

      if (item["selectedProductCode"] != null && item["selectedProductCode"] != "") 
      { 
       string strProductId = item["selectedProductCode"]; 
      } 
     } 
+0

'selectedproductId'를'if' 진술. – saber

+1

죄송합니다. 오타 오류. 그것은 selectedProductCode입니다. –

+1

속성 자체가 값이 아닌 동적 객체에서 누락되었을 수 있습니다. 따라서 표준 null 검사는 호출 예외를 throw합니다. 시도 {} catch {}는 작업을 수행하는 것 같습니다. – MikeW

1

사용하여 반사-시도 캐치보다 낫다, 그래서 이것은 내가 사용하는 기능입니다 : 다음

public static bool doesPropertyExist(dynamic obj, string property) 
{ 
    return ((Type)obj.GetType()).GetProperties().Where(p => p.Name.Equals(property)).Any(); 
} 

..

if (doesPropertyExist(myDynamicObject, "myProperty")){ 
    // ... 
} 
관련 문제