搜索不存在的对象名时检测错误

时间:2013-04-12 17:01:21

标签: c# object

在下面的代码中,当对象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
    .....
}

1 个答案:

答案 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
}