在对象的构造函数中使用扩展方法,其中“Me”是是 ByRef 目标对象
考虑以下问题:
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这里的问题是 VB.Net 支持多种使用 ByRef 参数的方式。 中对这些类型进行了详细解释
这里发生的事情是
Me
不是一个可分配的值。因此,VB 编译器不会将Me
作为 byRef 参数传递,而是传递一个临时参数。这通常被称为“Copy Back ByRef”。它有效地生成以下代码对于
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 passingMe
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 codeThere is no way to work around this in the case of
Me
because it's not assignable. In the case of the local variablefoo
though this works as expected becausefoo
is a valid ByRef value.