如何在With ... End With中访问对象本身

15 vb.net with-statement

一些代码来说明我的问题:

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
Run Code Online (Sandbox Code Playgroud)

Pat*_*ald 19

除了重复对象本身的名称之外,无法引用With语句中引用的对象.

编辑

如果您真的想要,可以修改AnObject以返回对自身的引用

Public Function Self() as TypeOfAnObject
    Return Me
End Get
Run Code Online (Sandbox Code Playgroud)

然后你可以使用以下代码

With Test.AnObject
    Test2.Subroutine(.Self())
End With
Run Code Online (Sandbox Code Playgroud)

最后,如果您无法修改AnObject的代码,您可以(但不一定应该)通过扩展方法完成相同的操作.一个通用解决方案是:

' Define in a Module
<Extension()>
Public Function Self(Of T)(target As T) As T
    Return target
End Function
Run Code Online (Sandbox Code Playgroud)

如此称呼:

Test2.Subroutine(.Self())
Run Code Online (Sandbox Code Playgroud)

要么

With 1
   a = .Self() + 2 ' a now equals 3
End With
Run Code Online (Sandbox Code Playgroud)


Mar*_*ell 6

我怀疑你不得不重复自己.如果表达式(获取对象)很昂贵,那么可能首先将其放入变量中,然后在该变量中使用该变量With,或者With完全删除:

tmp = Test.AnObject;
tmp.Something = 1337;
...
Test2.Subroutine(tmp);
Run Code Online (Sandbox Code Playgroud)


Chr*_*isA 5

正如其他人所说,你将不得不写作

Test2.Subroutine(Test.AnObject)
Run Code Online (Sandbox Code Playgroud)

这是为什么值得With对VB.Net中的构造稍微小心的一个很好的例子.我的观点是,为了使它值得使用,你真的需要设置多个或两个属性,和/或在With语句中对对象调用多个或两个方法.

如果有很多东西,并且你没有穿插它.SomeProperty =,或者.DoSomething与其他东西一起散布它,这对可读性来说是一个极好的帮助.

相反,在一堆其他东西中散布的几个点实际上比完全不使用更难阅读With.

在这种情况下,.角色本身很容易在视觉上迷失,尽管当然,它在语法上是一致的.

我猜他们只是选择不实施它.VB并不是他们想要鼓励单字符语言元素的那种语言,作为VB.Net的重度用户,我大致同意这一点.

底线:如果你使用的With子句包含很多包含的元素,那么必须引用对象本身并不是什么大问题.如果你只使用一两个,最好不要With在第一时间使用一个条款.