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
    .....
}
4

1 回答 1

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
}
于 2013-04-12T17:08:05.063 回答