Look at the code below, what do you think it will output?
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();
}
}
Guess first, it seems to be "base initializer, base constructor, Derived initializer, Derived constructor".
In fact, the initialization of class members should be performed first, in order from derived to base, then two constructors, sorted from base to derived.
This approach is very meaningful, in the class inheritance system in the deeper class (farther from the System.Object) will depend on the lighter class (closer to the System.Object). But many people will believe that the order of invocation should be equivalent to the following pseudocode:
// 期望的顺序
BaseConstructor()
{
ObjectConstructor();
baseFoo = new Foo("Base initializer");
Console.WriteLine("Base constructor");
}
DerivedConstructor()
{
BaseConstructor();
derivedFoo = new Foo("Derived initializer");
Console.WriteLine("Derived constructor");
}