在C#中,是在类成员初始化时生成的默认构造函数吗?

问题描述:

假设我初始化类的成员如下:在C#中,是在类成员初始化时生成的默认构造函数吗?

class A 
{ 
    public int i=4; 
    public double j=6.0; 
} 

该编译器生成在这种情况下默认的构造函数?一般来说,我知道一个构造函数可能会初始化类实例变量的值,也可能执行一些适合该类的其他初始化操作。但是在上面的例子中,我已经初始化了构造函数外部的值ij。在这种情况下,编译器是否仍然生成默认的构造函数?如果是这样,那么默认的构造函数是做什么的?

+0

我已经对您的问题进行了大量修改,以阐明我认为您正在尝试提问的内容,并可能会引起更多关注。如果我错误地判断了你的意图,请回滚我的编辑或进一步编辑。 – DavidRR 2015-12-02 15:47:36

在这种情况下,编译器仍然会生成默认构造函数。构造函数处理i和j的初始化。如果你看看IL这是显而易见的。

.class auto ansi nested private beforefieldinit A 
    extends [mscorlib]System.Object 
{ 
    .method public hidebysig specialname rtspecialname instance void .ctor() cil managed 
    { 
     .maxstack 8 
     L_0000: ldarg.0 // pushes "this" onto the stack 
     L_0001: ldc.i4.4 // pushes 4 (as Int32) onto the stack 
     L_0002: stfld int32 TestApp.Program/A::i // assigns to i (this.i=4) 
     L_0007: ldarg.0 // pushes "this" onto the stack 
     L_0008: ldc.r8 6 // pushes 6 (as Double) onto the stack 
     L_0011: stfld float64 TestApp.Program/A::j // assigns to j (this.j=6.0) 
     L_0016: ldarg.0 // pushes "this" onto the stack 
     L_0017: call instance void [mscorlib]System.Object::.ctor() // calls the base-ctor 
     /* if you had a custom constructor, the body would go here */ 
     L_001c: ret // and back we go 
    } 
+2

注明OP;希望没关系 – 2010-09-06 05:38:03

+0

谢谢Marc。好主意。 – 2010-09-06 05:45:57

上面的变量初始化会先运行。然后你的构造函数中的任何东西都会在后面运行。

你可以在official ECMA language standard中阅读这些东西。第17.4.5章讨论了这个特定的问题,基本上说明字段将被默认值初始化为任何类型的默认值(在你的情况下分别为0或0.0),然后按照他们的顺序执行值初始化在源文件中声明。

+0

+1参照标准规范 – jgauffin 2010-09-06 06:46:06