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

查看:612
本文介绍了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?

推荐答案

的顺序是:


  • 成员变量的初始化等级为默认值的所有类

然后先从最派生类:


  • 变量初始化大多为衍生型执行

  • 构造函数链的作品出来基类构造函数将被称为该

  • 的基类被初始化(递归这一切:)

  • 在链中的构造体在这一类中执行(请注意,可以有多个,如果他们正在与链美孚():这个(...)

  • 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中,基类初始化的的变量初始化中运行。如果你曾经端口的任何code,这是了解一个重要的区别:)

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天全站免登陆