为什么在VB.NET中传递“Me”ByRef是合法的?
刚才我震惊地发现以下是合法的(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规范.
(都强调我的) 因此,编译器将创建一个临时变量,该变量分配给Me的值作为ByRef参数传递.返回时,由于Me不是变量,因此不会生成结果值的副本. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |