构造函数链订单 [英] Constructor Chaining Order
问题描述
如果您使用链语法构造函数调用:
If you chain constructor calls using the syntax:
public frmConfirm(): this(1)
在被称为重载的构造函数?此外,有人可以证实,如果类是一种形式,问题就不必在这两个构造函数在InitializeComponent()调用产生的?
when is the overloaded constructor called? Also, can somebody confirm that if the class is a form, problems will arise from having the InitializeComponent() call in both constructors?
推荐答案
链式构造函数将被调用立即之前定义构造函数体。产生的IL序列是即时呼叫
其他构造,其次是在构造函数中语句生成的IL。
The chained constructor will be called immediately prior to the body of the defining constructor. The IL sequence generated is an immediate call
to the other constructor, followed by the IL generated from the statements in the constructor.
因此,如果您链另一个构造和构造函数调用的InitializeComponent()
调用构造函数不应该调用此方法。
So if you chain to another constructor and that constructor calls InitializeComponent()
the calling constructor should not call this method.
,例如,给定此示例类:
For example, given this sample class:
class Foo {
public int A, B;
public Foo() : this(1) {
B = 2;
}
public Foo(int a) {
A = a;
}
}
这是生成的IL:
.class private auto ansi beforefieldinit Foo
extends [mscorlib]System.Object
{
.field public int32 A
.field public int32 B
// method line 1
.method public hidebysig specialname rtspecialname
instance default void '.ctor' () cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldc.i4.1
IL_0002: call instance void class Foo::'.ctor'(int32)
IL_0007: ldarg.0
IL_0008: ldc.i4.2
IL_0009: stfld int32 Foo::B
IL_000e: ret
} // end of method Foo::.ctor
// method line 2
.method public hidebysig specialname rtspecialname
instance default void '.ctor' (int32 a) cil managed
{
.maxstack 8
IL_0000: ldarg.0
IL_0001: call instance void object::'.ctor'()
IL_0006: ldarg.0
IL_0007: ldarg.1
IL_0008: stfld int32 Foo::A
IL_000d: ret
} // end of method Foo::.ctor
} // end of class Foo
请注意,无参数的构造函数分配2到b场前调用其他构造函数。
Note that the no-arg constructor calls the other constructor before assigning 2 to the B field.
这篇关于构造函数链订单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!