变量初始化,基类构造器,基类构造器中调用虚函数,子类构造器
2018-01-22 11:34 Dirichlet 阅读(257) 评论(0) 编辑 收藏 举报正确顺序:变量初始化代码,基类变量初始化代码,基类构造器,基类构造器中调用虚函数,子类自己的构造器。
基类构造器中调用的虚函数会起作用,因为此时对象已经构建好了,但是只是执行了变量的初始化代码,还没有经过子类自己的构造器的初始化。
using System; namespace ConsoleApp3 { class A { public A() { PrintFields(); } public virtual void PrintFields() { } } class B:A { int x = 1; int y; public B() { y = 1; } public override void PrintFields() { Console.WriteLine($"x={x}, y={y}"); } } interface IInterface { void test(); void test(int a); } class Program { static void Main(string[] args) { A b = new B(); } } }
结果
x=1, y=0