VB.NET 中类字段的初始化顺序是否会受到对其他字段的引用的影响?
采取以下示例代码:
Class Foo
ReadOnly name As String
Public Sub New(name As String, dependentUpon As Foo)
Me.name = name
Console.Write("{0} created. ", name)
Console.WriteLine("Dependent upon {0}.", If(dependentUpon IsNot Nothing,
dependentUpon.Name,
"nothing"))
End Sub
End Class
Class Bar
ReadOnly dependent As New Foo("Dependent", independent) ' <-- !!!
ReadOnly independent As New Foo("Independent", Nothing)
End Class
New Bar()
的输出是:
Dependent created. Dependent upon nothing.
Independent created. Dependent upon nothing.
字段的初始化顺序似乎与源代码中出现的顺序相同,这 (a) 会导致意外结果,并且 ( b) 似乎有点令人费解,因为通常不允许从 .NET 中读取未初始化的变量,但这似乎在上面工作正常。
我希望 VB.NET 足够聪明,能够首先初始化引用的字段,然后才初始化那些引用它的字段;即我希望看到这个输出:
Independent created. Dependent upon nothing.
Dependent created. Dependent upon Independent.
Does 有人知道如何让 VB.NET 表现得像这样,而不必简单地交换 dependent
和 的声明顺序独立于类
Bar
内?
Take this sample code:
Class Foo
ReadOnly name As String
Public Sub New(name As String, dependentUpon As Foo)
Me.name = name
Console.Write("{0} created. ", name)
Console.WriteLine("Dependent upon {0}.", If(dependentUpon IsNot Nothing,
dependentUpon.Name,
"nothing"))
End Sub
End Class
Class Bar
ReadOnly dependent As New Foo("Dependent", independent) ' <-- !!!
ReadOnly independent As New Foo("Independent", Nothing)
End Class
The output of New Bar()
is:
Dependent created. Dependent upon nothing.
Independent created. Dependent upon nothing.
It seems fields are initialized in the same order as they appear in the source code, which (a) leads to an unexpected result, and (b) seems a little puzzling, given that one is normally not permitted to read from uninitialized variables in .NET, yet that seems to be working fine above.
I would've expected VB.NET to be smart enough to initialize referenced fields first, and only then those that reference it; i.e. I'd have liked to see this output instead:
Independent created. Dependent upon nothing.
Dependent created. Dependent upon Independent.
Does someone know a way how to get VB.NET to behave like that instead, without simply having to swap the declaration order of dependent
and independent
inside class Bar
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
字段始终按照声明的顺序进行初始化。
对访问未初始化变量的限制仅适用于本地变量,不适用于字段。 (这太难执行了)
Fields are always initialized in the order they're declared.
The restriction against accessing uninitialized variables applies only to local variables, not fields. (that would be too hard to enforce)