正确顺序:变量初始化代码,基类构造器,基类构造器中调用虚函数,子类本身的构造器。ide
基类构造器中调用的虚函数会起做用,由于此时对象已经构建好了,可是只是执行了变量的初始化代码,尚未通过子类本身的构造器的初始化。函数
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(); } } }
结果spa
x=1, y=0