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#的标准行为?