我在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)
答案 0 :(得分:1)
如果您已经需要执行呼叫,那么尝试呼叫并在失败时执行不同的操作会更容易,也更便宜。
try
{
PropertyDescriptor.GetValue(...);
}
catch (TargetException ex)
{
// do the thing you would do if the object wasn't valid.
}