在对象的构造函数中使用扩展方法,其中“Me”是是 ByRef 目标对象

发布于 2024-08-20 21:19:23 字数 645 浏览 6 评论 0原文

考虑以下问题:

Public Module Extensions
    <Extension()> _
    Public Sub Initialize(ByRef Target as SomeClass, ByVal SomeParam as Something )
        ...
        Target  = SomethingElse
    end Sub
End Module

Class SomeClass
...

    sub New(ByVal SomeParam as Something )
       Me.Initialize(SomeParam)
    end sub

    sub New()

    end sub

End Class


'Case 1: Doesnt Work...why????:

    Dim foo as new SomeClass(SomeParam) 'foo remains uninitialized


'Case 2: Does Work:
    Dim foo as new SomeClass()
    foo.Initialize(SomeParam) 'foo is initialized

问题: 为什么情况 1 无法按预期初始化对象?

Consider the following:

Public Module Extensions
    <Extension()> _
    Public Sub Initialize(ByRef Target as SomeClass, ByVal SomeParam as Something )
        ...
        Target  = SomethingElse
    end Sub
End Module

Class SomeClass
...

    sub New(ByVal SomeParam as Something )
       Me.Initialize(SomeParam)
    end sub

    sub New()

    end sub

End Class


'Case 1: Doesnt Work...why????:

    Dim foo as new SomeClass(SomeParam) 'foo remains uninitialized


'Case 2: Does Work:
    Dim foo as new SomeClass()
    foo.Initialize(SomeParam) 'foo is initialized

Question:
Why is Case 1 failing to initialize the object as expected?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

牵你的手,一向走下去 2024-08-27 21:19:23

这里的问题是 VB.Net 支持多种使用 ByRef 参数的方式。 中对这些类型进行了详细解释

这里发生的事情是 Me 不是一个可分配的值。因此,VB 编译器不会将 Me 作为 byRef 参数传递,而是传递一个临时参数。这通常被称为“Copy Back ByRef”。它有效地生成以下代码

Dim temp = Me
Initialize(temp, SomeParam)

对于 Me ,无法解决此问题,因为它不可分配。在局部变量 foo 的情况下,这会按预期工作,因为 foo 是一个有效的 ByRef 值。

The problem here is that VB.Net supports multiple ways of using ByRef parameters. I did a detailed explanation of the types in a recent blog entry

What's happening here is that Me is not an assignable value. So instead of passing Me as a byRef parameter, the VB compiler will instead pass a temporary. This is loosely known as "Copy Back ByRef". It effectively generates the following code

Dim temp = Me
Initialize(temp, SomeParam)

There is no way to work around this in the case of Me because it's not assignable. In the case of the local variable foo though this works as expected because foo is a valid ByRef value.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文