我正在使用WinForms应用程序并使用BindingList数据源。我需要用PropertyDescriptor检查对象是否有效。因为 PropertyDescriptor.GetValue(object obj)
将适用于有效的对象。但有时我有“TargetInvocationException”。所以我想在得到这个值之前检查一下这个对象是否有效。如何检查PropertyDescriptor中的有效对象?
[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)
'try/catch'太贵了吗?应该可以在['CheckConsistency'](https://referencesource.microsoft.com/#mscorlib/system/reflection/methodinfo.cs,9d661e8f9f8783cd)方法中检查类型(您可能必须使用反射来访问私有成员)。 – Sinatr
你能显示你的代码吗? – Usman