简体   繁体   中英

Intercept property assignment to catch InvalidCastException

I am trying to intercept property setter using postsharp LocationInterceptionAspect to perform some validation before setting the value to private members. It works fine however if the value data type is not compatible with property data type it throws InvalidCastException and does not invoke OnSetValue . Is there any way I can generically catch this exception, nullify the value and then process with setter?

Property Validator Aspect:

<Serializable()>
Public Class PropertyValidatorAttribute
    Inherits LocationInterceptionAspect

    Public Overrides Sub OnSetValue(args As LocationInterceptionArgs)
        'Perform validation here

        args.ProceedSetValue()
    End Sub
End Class

Class where aspect is used:

Public Enum MyEnum
    A = 1
    B = 2
End Enum

Public Class SampleClass
    <PropertyValidator()>
    Public Property SomeProperty As MyEnum
End Class

Main:

Sub Main()
    Dim x As New SampleClass()
    x.SomeProperty = "X"
End Sub

I'm not 100% sure about vb.net but what is really happinging is that this is translated to

x.SetSomeProperty((MyEnum)"X")

This is just plain .NET. after that postsharps try to incercept your method but it will insert itself between the cast and the SetSomeProperty. (you could verify this with ilspy). This means you can't intercept the cast.

Your project uses OptionStrict off and instead of

x.SomeProperty = "X"

VisualBasic compiler generates

Dim temp = CType("X", MyEnum)
x.SomeProperty = temp

The InvalidCastException is thrown by CType expression even before the getter of SomeProperty is invoked as Batavia points out.

If you would set OptionStrict on (/optionstrict+ on command line), then you would get a build error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM