使用了继承之后,当我们初始化一个子类时,除了会调用子类的构造函数外,同时也会调用基类的构造函数。子类的初始化顺序如下:
① 初始化类的实例字段;
② 调用基类的构造函数,如果没有指明基类,则调用System.Object的构造函数;
③ 调用子类的构造函数。
如下实例:
static void Main(string[] args) { ChildA child = new ChildA(); child.Print(); Console.Read(); }
public class Parent { public Parent() { Console.WriteLine("基类构造函数被调用"); } } public class ChildA : Parent { //创建一个ChildA对象时, //① 初始化它的实例字段 private int FieldA = 3; public ChildA() { Console.WriteLine("子类构造函数被调用"); } public void Print() { Console.WriteLine(FieldA); } }