![](/img/trans.png)
[英]How to override PropertyDescriptor.GetValue and PropertyDescriptor.SetValue for dynamic object in .NET 4
[英]How to check valid object in PropertyDescriptor?
我正在WinForms应用程序中工作,并使用了BindingList数据源。 我需要使用PropertyDescriptor检查对象是否有效。 因为PropertyDescriptor.GetValue(object obj)
将适用于有效对象。 但有时我有“ TargetInvocationException ”。 所以我想在获取值之前检查该对象是否有效。
[ 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
{
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.