Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
721 views
in Technique[技术] by (71.8m points)

vb.net - How to access the object itself in With ... End With

Some code to illustrate my question:

With Test.AnObject

    .Something = 1337
    .AnotherThing = "Hello"

    ''// why can't I do this to pass the object itself:
    Test2.Subroutine(.)
    ''// ... and is there an equivalent, other than repeating the object in With?

End With
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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
<Extension()>
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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...