简体   繁体   English

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

[英]How to check valid object in PropertyDescriptor?

I'm working in WinForms application and used the BindingList datasource. 我正在WinForms应用程序中工作,并使用了BindingList数据源。 I need to check the whether the object is valid or not with PropertyDescriptor . 我需要使用PropertyDescriptor检查对象是否有效。 because PropertyDescriptor.GetValue(object obj) will works for valid object. 因为PropertyDescriptor.GetValue(object obj)将适用于有效对象。 but sometimes i has the " TargetInvocationException ". 但有时我有“ TargetInvocationException ”。 So i want to check if that object is valid or not before get the value. 所以我想在获取值之前检查该对象是否有效。

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

here is the 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)

In the case that you will already need to execute the call, it will be far easier and less expensive to just try the call and do something different if it fails. 在您已经需要执行调用的情况下,尝试调用并在失败时执行其他操作将变得更加容易且成本更低。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM