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

Nis*_*mar 5 c# constructor initialization

假设我初始化类的成员,如下所示:

class A 
{
    public int i=4;
    public double j=6.0;
}
Run Code Online (Sandbox Code Playgroud)

在这种情况下编译器是否生成默认构造函数?

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

Bri*_*sen 11

在这种情况下,编译器仍会生成默认构造函数.构造函数处理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
   }
Run Code Online (Sandbox Code Playgroud)

  • 注释为OP; 希望没关系 (2认同)