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是合法的? (是否有一些向后兼容性解释?)
>我是否正确地说编译器会覆盖执行此操作的行为?如果没有,我错过了什么?
解决方法
11.4.3 Instance Expressions
An instance expression is the keyword
Me
,MyClass
,orMyBase
. 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不是变量,因此不会生成结果值的副本.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。