首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在PropertyDescriptor中检查有效对象?

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

Stack Overflow用户
提问于 2017-03-07 13:19:23
回答 1查看 436关注 0票数 0

我在WinForms应用程序中工作,并使用BindingList数据源。我需要用PropertyDescriptor.检查对象是否有效。因为PropertyDescriptor.GetValue(object obj)将适用于有效的对象。但有时我有"TargetInvocationException".因此,在得到值之前,我想检查该对象是否有效。

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

下面是堆栈跟踪:

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

发布于 2017-03-07 13:29:41

在您已经需要执行调用的情况下,只要尝试调用并在失败时执行一些不同的操作,就会简单得多,成本也会低得多。

代码语言:javascript
复制
try 
{
    PropertyDescriptor.GetValue(...);
}
catch (TargetException ex)
{
    // do the thing you would do if the object wasn't valid.
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42649406

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档