看看下面这段代码,你觉得它会输出什么呢?
class Foo
{
public Foo(string s)
{
Console.WriteLine("Foo constructor: {0}", s);
}
public void Bar(){}
}
class Base
{
readonly Foo baseFoo = new Foo("Base initializer");
public Base()
{
Console.WriteLine("Base constructor");
}
}
class Derived : Base
{
readonly Foo derivedFoo = new Foo("Derived initializer.");
public Derived()
{
Console.WriteLine("Derived constructor");
}
}
class Program
{
static void Main(string[] args)
{
new Derived();
}
}
总结,类成员的初始化要先于类的构造器执行.
基类的构造器先于子类的构造器的执行.