构造函数链序
如果使用以下语法链接构造函数调用:
public frmConfirm(): this(1)
何时调用重载构造函数?
另外,有人可以确认,如果该类是一个表单,那么在两个构造函数中调用 InitializeComponent()
就会出现问题吗?
If you chain constructor calls using the syntax:
public frmConfirm(): this(1)
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
链式构造函数将在定义构造函数的主体之前立即调用。生成的 IL 序列是对另一个构造函数的立即
调用
,后面是从构造函数中的语句生成的 IL。因此,如果您链接到另一个构造函数,并且该构造函数调用
InitializeComponent()
,则调用构造函数不应调用此方法。例如,给定以下示例类:
这是生成的 IL:
请注意,无参数构造函数在将 2 分配给 B 字段之前调用另一个构造函数。
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.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:
This is the generated IL:
Note that the no-arg constructor calls the other constructor before assigning 2 to the B field.
首先调用
this(1)
构造函数。至于你的第二个问题,由于
InitializeComponent
和表单继承的其他问题,我建议你使用组合而不是继承。The
this(1)
constructor is called first.As far as your second question goes, because of the
InitializeComponent
and other issues with form inheritance, I'd suggest you use composition instead of inheritance.寻找此类问题答案的地方是 C# 语言规范。在构造函数初始值设定项部分中,您可以阅读(重点是我的):
进一步阅读表明:
base(arguments)
形式的实例构造函数初始值设定项,则将调用直接基类的构造函数。this(argument)
形式的实例构造函数初始值设定项,则将调用类本身中的构造函数。base()
。The place to look for answers on a question like this is the C# Language Specification. In the section Constructor initializers you can read (emphasis is mine):
Further reading shows that:
base(arguments)
, a constructor from the direct base class will be invoked.this(argument)
, a constructor in the class itself will be invoked.base()
will be added automatically.