在基类构造器中调用虚方法需谨慎最近,在基类的构造函数中调用虚方法时,发现了一个问题。先把问题重现如下:
class PRogram
{
static void Main(string[] args)
{
var c = new Chinese(18);
Console.ReadKey();
}
}
public class People
{
public int Age { get; protected set; }
protected People()
{
this.Say();
}
public virtual void Say()
{
Console.WriteLine(string.Format("基类说我今年{0}岁了", Age));
}
}
public class Chinese : People
{
public Chinese(int age)
{
this.Age = age;
}
public override void Say()
{
Console.WriteLine(string.Format("子类说我今年{0}岁了",Age));
}
}
运行以上的代码,结果会是以下两种情况之一吗?基类说我今年18岁了子类说我今年18岁了
都不是!而是:
为什么? →调用子类构造函数new Chinese(18) →先调用父类无参构造函数,并调用虚方法