繁体   English   中英

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

[英]In C#, is a default constructor generated when class members are initialized?

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

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

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

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

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

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

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

暂无
暂无

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

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