0

我在 WinForms 应用程序中工作并使用了 BindingList 数据源。我需要使用PropertyDescriptor检查对象是否有效。因为 PropertyDescriptor.GetValue(object obj)将适用于有效对象。但有时我有“ TargetInvocationException ”。所以我想在获取值之前检查该对象是否有效。

[ https://i.stack.imgur.com/VsdeW.png]

这是堆栈跟踪:

System.Reflection.TargetException: Object does not match target type.
   at System.Reflection.RuntimeMethodInfo.CheckConsistency(Object target)
   at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.SecurityUtils.MethodInfoInvoke(MethodInfo method, Object target, Object[] args)
   at System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component)
   --- End of inner exception stack trace ---
   at System.ComponentModel.ReflectPropertyDescriptor.GetValue(Object component)
4

1 回答 1

1

在您已经需要执行调用的情况下,尝试调用并在失败时执行不同的操作会更容易且成本更低。

try 
{
    PropertyDescriptor.GetValue(...);
}
catch (TargetException ex)
{
    // do the thing you would do if the object wasn't valid.
}
于 2017-03-07T13:29:41.357 回答