C#构造函数执行顺序 [英] C# constructor execution order

查看:135
本文介绍了C#构造函数执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,当您执行

Class(Type param1, Type param2):base(param1) 

是先执行的类的构造函数,然后调用超类构造函数,还是先调用基类构造函数?

is the constructor of the class executed first, and then the superclass constructor is called or does it call the base constructor first?

推荐答案

顺序是:


  • 成员变量被初始化为层次结构中所有类的默认值

然后从最多派生类开始:

Then starting with the most derived class:


  • 为最派生类型执行变量初始值设置

  • 构造函数链

  • 这个类中的链中的构造函数体被执行(注意,如果它们与 Foo():this(...)等链接,可以多于一个

  • Variable initializers are executed for the most-derived type
  • Constructor chaining works out which base class constructor is going to be called
  • The base class is initialized (recurse all of this :)
  • The constructor bodies in the chain in this class are executed (note that there can be more than one if they're chained with Foo() : this(...) etc

请注意,在Java中,基类在变量初始化运行之前被初始化。如果您曾经移植任何代码,这是一个重要的区别:)

Note that in Java, the base class is initialized before variable initializers are run. If you ever port any code, this is an important difference to know about :)

我有一个有更多详情的页面

这篇关于C#构造函数执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆