简体   繁体   English

公共成员与C#中的类的构造函数?

[英]Public Members vs Constructor of a Class in C#?

I have a doubt. 我有个疑问。

1. namespace JIMS.ViewModel.Stock
2. {
3.     internal class StockGroupViewModel : JIMS.ViewModel.BaseViewModel
4.     {
5.         JIMSEntities dbContext = new JIMSEntities();
6. 
7.         public StockGroupViewModel()
8.         {                     
9.          dbContext = new JIMSEntities();
10.        }
11.    }
12. }

I have this class. 我有这门课。 And i want to know which is called first. 而且我想知道哪个被称为第一个。 when i create an instance of this class 当我创建这个类的实例

StockGroupViewModel s = new StockGroupViewModel();

Line 5 or Line 9.

Line 5 - it's a field initializer which is executed before any code within the constructor. 第5行 - 它是一个字段初始值设定项,它在构造函数中的任何代码之前执行。

From the spec: 从规格:

10.5.5.2 Instance field initialization 10.5.5.2实例字段初始化

The instance field variable initializers of a class correspond to a sequence of assignments that are executed immediately upon entry to any one of the instance constructors (§10.11.1) of that class . 类的实例字段变量初始值设定项对应于在进入该类的任何一个实例构造函数(第10.11.1节)后立即执行的赋值序列。 The variable initializers are executed in the textual order in which they appear in the class declaration. 变量初始值设定项以它们出现在类声明中的文本顺序执行。 The class instance creation and initialization process is described further in §10.11. 类实例创建和初始化过程在第10.11节中进一步描述。

Field initializers called prior to body of constructor. 字段初始值设定项在构造函数体之前调用。 So, line 5 called before line 9. 因此,第9行在第9行之前调用。

第5行,在调用构造函数之前初始化字段。

The compiler will embed the field initializer in the code for the constructor, so that is called first and then the field is initialized again by the call in the constructor. 编译器会将字段初始值设定项嵌入到构造函数的代码中,因此首先调用该字段, 然后通过构造函数中的调用再次初始化该字段。 Looking at the IL for the code makes this very obvious. 查看IL代码使得这非常明显。

Eg code like this 例如这样的代码

class Foo
{
    StringBuilder sb = new StringBuilder(1);

    public Foo()
    {
        sb = new StringBuilder(2);
    }
}

looks like this at the IL level 在IL级别看起来像这样

.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
    .maxstack 8
    L_0000: ldarg.0 
    L_0001: ldc.i4.1  <-- ARGUMENT = 1
    L_0002: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor(int32)
    L_0007: stfld class [mscorlib]System.Text.StringBuilder playground.Foo::o
    L_000c: ldarg.0 
    L_000d: call instance void [mscorlib]System.Object::.ctor()
    L_0012: nop 
    L_0013: nop 
    L_0014: ldarg.0 
    L_0015: ldc.i4.2  <-- ARGUMENT = 2
    L_0016: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor(int32)
    L_001b: stfld class [mscorlib]System.Text.StringBuilder playground.Foo::o
    L_0020: nop 
    L_0021: ret 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM