0

私はWinFormsアプリケーションで作業しており、BindingListデータソースを使用しています。オブジェクトが有効かどうかは、PropertyDescriptorで確認する必要があります。 PropertyDescriptor.GetValue(object obj)が有効なオブジェクトとして動作するためです。しかし時々私は "TargetInvocationException"を持っています。だから私はそのオブジェクトが有効かどうか、値を取得する前にチェックしたい。PropertyDescriptorで有効なオブジェクトをチェックする方法は?

[ここ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) 
+1

'try/catch'は高価すぎますか? [CheckConsistency'](https://referencesource.microsoft.com/#mscorlib/system/reflection/methodinfo.cs,9d661e8f9f8783cd)メソッドのようにタイプをチェックすることができます(リフレクションを使用してプライベートにアクセスする必要があるかもしれません)メンバー)。 – Sinatr

+0

あなたのコードを表示できますか? – Usman

答えて

1

、それだけで通話を試してみてやってはるかに容易かつ安価になりますもし失敗すれば何か違う。

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

こんにちは@ Caesay、あなたの提案をありがとう。実際には、値を取得する前にプロパティを検証したい(PropertyDescriptor.GetValue)。ご懸念があれば教えてください。 – Prithiv

関連する問題