如何在 With ... End With 中访问对象本身 [英] How to access the object itself in With ... End With

查看:19
本文介绍了如何在 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

推荐答案

没有办法引用 With 语句中引用的对象,只能重复对象本身的名称.

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

如果你真的想,你可以修改你的对象以返回对自身的引用

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

这样称呼:

Test2.Subroutine(.Self())

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

这篇关于如何在 With ... End With 中访问对象本身的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆