2013-04-12 39 views
0

在下面當MyGlobals.ListOfItemsToControl[i].sItemName不在對象HWRes.HWResObj存在代碼對象的名字,我想檢測這個問題,而跳到catch語句。檢測錯誤,同時尋找不存在

我該如何做到這一點?

try 
{ 
    String HWTemp = ""; 
    // Ref http://stackoverflow.com/questions/15628140/c-sharp-eliminate-switch-requirement 
    HWTemp = HWRes.HWResObj.GetType().GetProperty(MyGlobals.ListOfItemsToControl[i].sItemName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance).GetValue(HWRes.HWResObj, null).ToString(); 


// Somehow here I should detect if the value MyGlobals.ListOfItemsToControl[i].sItemName does not exist in the object HWRes.HWResObj 
// Detect issue without jumping to catch 

} 
catch 
{ 
    // I dont want to go here when MyGlobals.ListOfItemsToControl[i].sItemName does not exist in the object HWRes.HWResObj 
    ..... 
} 

回答

2

檢查從GetProperty返回值是這樣的:

var property = HWRes.HWResObj.GetType().GetProperty(MyGlobals.ListOfItemsToControl[i].sItemName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance); 
if (property != null) 
{ 
    string HWTemp = property.GetValue(HWRes.HWResObj, null).ToString(); 
} 
else 
{ 
    // property does not exist 
}