如何在PropertyDescriptor中检查有效对象?

时间:2017-03-07 13:19:23

标签: c# winforms properties system.reflection targetinvocationexception

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

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

这是stacktrace:

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)

1 个答案:

答案 0 :(得分:1)

如果您已经需要执行呼叫,那么尝试呼叫并在失败时执行不同的操作会更容易,也更便宜。

try 
{
    PropertyDescriptor.GetValue(...);
}
catch (TargetException ex)
{
    // do the thing you would do if the object wasn't valid.
}