0

我正在使用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) 
+1

'try/catch'太贵了吗?应该可以在['CheckConsistency'](https://referencesource.microsoft.com/#mscorlib/system/reflection/methodinfo.cs,9d661e8f9f8783cd)方法中检查类型(您可能必须使用反射来访问私有成员)。 – Sinatr

+0

你能显示你的代码吗? – Usman

回答

1

在这种情况下,你已经将需要执行的号召,这将是更容易,更便宜,只是尝试呼叫和做如果失败,则会有所不同。

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

Hi @ Caesay,谢谢你的建议。其实我想在获取值(PropertyDescriptor.GetValue)之前验证属性。如果有任何问题,请让我知道。 – Prithiv