获取此示例代码:
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.
有人知道如何让VB.NET像这样行事,而不必简单地交换dependent
independent
Bar
内的{{1}}和{{1}}的声明顺序吗?
答案 0 :(得分:2)
字段始终按照声明的顺序初始化。
访问未初始化变量的限制仅适用于本地变量,而不适用于字段。 (这太难以执行)