开发者

Can the initialization order of class fields in VB.NET be influenced by references to other fields?

开发者 https://www.devze.com 2023-03-13 19:57 出处:网络
Take this sample code: Class Foo ReadOnly name As String Public Sub New(name As String, dependentUpon As Foo)

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开发者_运维技巧?


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消