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.

有人知道如何让VB.NET表现得像这样,而不必简单地交换类Bardependentindependent的声明顺序吗?

字段总是按照声明的顺序进行初始化。

对访问未初始化变量的限制仅适用于本地变量,而不适用于字段。(这太难执行了)

相关内容

  • 没有找到相关文章