VB.NET 中类字段的初始化顺序是否会受到对其他字段的引用的影响?

发布于 2024-11-16 07:21:34 字数 1232 浏览 5 评论 0原文

采取以下示例代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

暖阳 2024-11-23 07:21:34

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

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

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)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文