加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

为什么在VB.NET中传递“Me”ByRef是合法的?

发布时间:2020-12-17 07:25:19 所属栏目:百科 来源:网络整理
导读:刚才我震惊地发现以下是合法的(C#等价物绝对不是): Class Assigner ''// Ignore this for now. Public Field As Integer ''// This part is not so weird... take another instance ByRef,''// assign it to a different instance -- stupid but whatever.
刚才我震惊地发现以下是合法的(C#等价物绝对不是):

Class Assigner
    ''// Ignore this for now.
    Public Field As Integer

    ''// This part is not so weird... take another instance ByRef,''// assign it to a different instance -- stupid but whatever. '
    Sub Assign(ByRef x As Assigner,ByVal y As Assigner)
        x = y
    End Sub

    ''// But... what's this?!?
    Sub AssignNew()
        ''// Passing "Me" ByRef???
        Assign(Me,New Assigner)
    End Sub

    ''// This is just for testing.
    Function GetField() As Integer
        Return Me.Field
    End Function
End Class

但是对我来说甚至更奇怪的是,它似乎没有达到我的期望:

Dim a As New Assigner With {.Field = 10}

a.AssignNew()

Console.WriteLine(a.GetField())

以上输出“10”,而非“0”,就像我认为的那样(虽然很自然,这种期望本身也注入了某种恐怖).因此,似乎您可以传递Me ByRef,但编译器会以某种方式覆盖(?)行为,就好像您已经通过Me ByVal一样.

>为什么通过Me ByRef是合法的? (是否有一些向后兼容性解释?)
>我是否正确地说编译器会覆盖执行此操作的行为?如果没有,我错过了什么?

解决方法

这种行为实际上直接来自Visual Basic规范.

11.4.3 Instance Expressions

An instance expression is the keyword Me,MyClass,or MyBase. An instance expression,which may only be used within the body of a non-shared method,constructor,or property accessor,is classified as a value.

9.2.5.2 Reference Parameters

If the type of the variable being passed to a reference parameter is not compatible with the reference parameter’s type,or if a non-variable is passed as an argument to a reference parameter,a temporary variable may be allocated and passed to the reference parameter. The value being passed in will be copied into this temporary variable before the method is invoked and will be copied back to the original variable (if there is one) when the method returns.

(都强调我的)

因此,编译器将创建一个临时变量,该变量分配给Me的值作为ByRef参数传递.返回时,由于Me不是变量,因此不会生成结果值的副本.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读