How to access the object itself in With … End With

后端 未结 4 1050
情歌与酒
情歌与酒 2020-12-03 17:32

Some code to illustrate my question:

With Test.AnObject

    .Something = 1337
    .AnotherThing = \"Hello\"

    \'\'// why can\'t I do this to pass the obj         


        
4条回答
  •  没有蜡笔的小新
    2020-12-03 18:15

    There is no way to refer to the object referenced in the With statement, other than repeating the name of the object itself.

    EDIT

    If you really want to, you could modify your an object to return a reference to itself

    Public Function Self() as TypeOfAnObject
        Return Me
    End Get
    

    Then you could use the following code

    With Test.AnObject
        Test2.Subroutine(.Self())
    End With
    

    Finally, if you cannot modify the code for an object, you could (but not necessarily should) accomplish the same thing via an extension method. One generic solution is:

    ' Define in a Module
    
    Public Function Self(Of T)(target As T) As T
        Return target
    End Function
    

    called like so:

    Test2.Subroutine(.Self())
    

    or

    With 1
       a = .Self() + 2 ' a now equals 3
    End With
    

提交回复
热议问题