2013-07-03 41 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

這會很簡單。設置檢查值爲空或空的條件。如果該值存在,則將該值分配給相應的數據類型。

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

您在'if'中檢查'selectedProductId'聲明。 – saber

+1

對不起。錯字錯誤。它被選中產品代碼。 –

+1

屬性本身可能從動態對象中丟失,而不是值 - 因此標準的空檢查會拋出調用異常 - 嘗試{} catch {}似乎可以完成這項工作 – MikeW

1

使用反射比的try-catch好,所以這是我使用的功能:

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

然後..

if (doesPropertyExist(myDynamicObject, "myProperty")){ 
    // ... 
} 
相關問題