加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

在调用基类型构造函数之前,是否可以强制VB.NET初始化实例变量?

发布时间:2020-12-16 23:51:44 所属栏目:大数据 来源:网络整理
导读:调试VB.NET中涉及实例变量初始化顺序的一个特别棘手的问题后,我发现我预期从C#的行为和VB.NET的实际行为之间有一个突破性的差异。 Nota bene:这个问题涉及到VB.NET和C#的行为略有不同。如果你是一个语言bigot,无法提供一个答案,而不是“这就是为什么你应
调试VB.NET中涉及实例变量初始化顺序的一个特别棘手的问题后,我发现我预期从C#的行为和VB.NET的实际行为之间有一个突破性的差异。

Nota bene:这个问题涉及到VB.NET和C#的行为略有不同。如果你是一个语言bigot,无法提供一个答案,而不是“这就是为什么你应该使用C#,noob”,你没有什么可以看到这里;请继续。

具体来说,我预计C# Language Specification(强调添加)概述的行为:

When an instance constructor has no constructor initializer,or it has a constructor initializer of the form base(...),that constructor implicitly performs the initializations specified by the variable-initializers of the instance fields declared in its class. This corresponds to a sequence of assignments that are executed immediately upon entry to the constructor and before the implicit invocation of the direct base class constructor. The variable initializers are executed in the textual order in which they appear in the class declaration.

与VB.NET语言规范有关Instance Constructors的部分对比,其中强调说:

When a constructor’s first statement is of the form MyBase.New(...),the constructor implicitly performs the initializations specified by the variable initializers of the instance variables declared in the type. This corresponds to a sequence of assignments that are executed immediately after invoking the direct base type constructor. Such ordering ensures that all base instance variables are initialized by their variable initializers before any statements that have access to the instance are executed.

这里的差异是显而易见的。 C#在调用基础构造函数之前初始化类级变量。 VB.NET完全相反,显然更喜欢在设置实例字段的值之前调用基本构造函数。

如果你想看到一些代码,this related question提供了一个更具体的发散行为的例子。不幸的是,它没有提供任何提示,如何可能强迫VB.NET进入下面的模型由C#建立。

我对于为什么两种语言的设计师选择这样不同的方法比我在可能的解决方案的问题不太感兴趣。最终,我的问题如下:有什么方法,我可以写或者结构我的代码在VB.NET强制实例变量在基本类型的构造函数被调用之前被初始化,作为在C#的标准行为?

如果你有在构建期间被调用的虚拟成员(反对最佳建议,但我们已经同意),那么你需要将你的初始化移动到一个单独的方法,可以保护自己免受多个调用(即if init已经发生,立即返回)。然后,在依赖于发生的初始化之前,虚拟成员和您的构造函数将调用该方法。

这有点凌乱,可能代表一个小的性能惩罚,但有一点你可以做在VB。

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读