在下面的代码中,当对象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
.....
}
答案 0 :(得分: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
}