1

拿这个示例代码:

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 表现得像这样,而无需简单地交换classdependentindependent内部的声明顺序Bar吗?

4

1 回答 1

2

字段始终按照它们声明的顺序进行初始化。

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

于 2011-06-19T16:56:08.437 回答