![](/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.