简体   繁体   中英

How to check valid object in PropertyDescriptor?

I'm working in WinForms application and used the BindingList datasource. I need to check the whether the object is valid or not with PropertyDescriptor . because PropertyDescriptor.GetValue(object obj) will works for valid object. but sometimes i has the " TargetInvocationException ". So i want to check if that object is valid or not before get the value.

[ 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.
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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