[英]IDictionary Property on model throwing System.InvalidCastException
[英]Intercept property assignment to catch InvalidCastException
我試圖使用postharp LocationInterceptionAspect
攔截屬性設置器,以便在將值設置為私有成員之前執行一些驗證。 它工作正常但是如果值數據類型與屬性數據類型不兼容,則它會拋出InvalidCastException
並且不調用OnSetValue
。 有什么方法可以一般地捕獲這個異常,使值無效然后用setter處理?
屬性驗證器方面:
<Serializable()>
Public Class PropertyValidatorAttribute
Inherits LocationInterceptionAspect
Public Overrides Sub OnSetValue(args As LocationInterceptionArgs)
'Perform validation here
args.ProceedSetValue()
End Sub
End Class
使用方面的類:
Public Enum MyEnum
A = 1
B = 2
End Enum
Public Class SampleClass
<PropertyValidator()>
Public Property SomeProperty As MyEnum
End Class
主要:
Sub Main()
Dim x As New SampleClass()
x.SomeProperty = "X"
End Sub
我對vb.net並不是100%肯定,但真正討厭的是這被翻譯成了
x.SetSomeProperty((MyEnum)"X")
這只是簡單的.NET。 之后,postharps試圖隱藏你的方法,但它會在強制轉換和SetSomeProperty之間插入。 (你可以用ilspy驗證這一點)。 這意味着你無法攔截演員陣容。
您的項目使用OptionStrict off
而不是
x.SomeProperty = "X"
VisualBasic編譯器生成
Dim temp = CType("X", MyEnum)
x.SomeProperty = temp
即使在Batavia指出調用SomeProperty的getter之前,CType表達式也會拋出InvalidCastException。
如果你OptionStrict on
(/ optionstrict +在命令行上)設置OptionStrict on
,那么你會得到一個構建錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.