【问题标题】:In C#, is a default constructor generated when class members are initialized?在C#中,初始化类成员时是否会生成默认构造函数?
【发布时间】:2011-04-08 15:03:42
【问题描述】:

假设我像这样初始化一个类的成员:

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

这种情况下编译器会生成默认构造函数吗?

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

【问题讨论】:

  • 我对您的问题进行了重大编辑,以澄清我认为您想问的问题,并可能引起更多关注。如果我误判了您的意图,请回滚我的编辑或进一步编辑。

标签: c# constructor initialization


【解决方案1】:

在这种情况下,编译器仍然会生成一个默认构造函数。构造函数处理 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
   }

【讨论】:

  • 为 OP 注释;希望没问题
【解决方案2】:

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

【讨论】:

    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 2015-02-24
      • 2015-01-12
      • 2011-08-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-28
      相关资源
      最近更新 更多