假设我初始化类的成员:
class A
{
public int i=4;
public double j=6.0;
}
编译器是否在这种情况下生成默认构造函数?
通常,我知道构造函数可以初始化类实例变量的值,也可以执行适合该类的其他一些初始化操作。但在上面的示例中,我已在构造函数之外初始化i
和j
的值。在这种情况下,编译器是否仍然生成默认构造函数?如果是这样,默认构造函数会做什么?
答案 0 :(得分: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
}
答案 1 :(得分:3)
您可以在official ECMA language standard中阅读这些内容。第17.4.5节讨论了这个特定的问题,基本上说明字段将使用类型具有的任何默认值进行默认初始化(在您的情况下分别为0或0.0),然后值初始化将按照它们的顺序执行在源文件中声明。
答案 2 :(得分:0)
首先运行上面的变量初始化。然后你的构造函数中的任何东西都会被运行。