C#类成员初始化与构造函数执行的顺序
先看一段程序:
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();
}
}
执行结果:

先执行类成员的初始化,顺序是从derived到base,然后是两个构造函数,顺序是从base从derived。
参考:
C# 小测试(一):类成员初始化与构造函数执行的顺序
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();
}
}执行结果:
先执行类成员的初始化,顺序是从derived到base,然后是两个构造函数,顺序是从base从derived。
这种方式是很有意义的,在类继承体系中层次较深的类(离System.Object较远)将依赖于较浅的类(离System.Object较近)。
参考:
C# 小测试(一):类成员初始化与构造函数执行的顺序
Why Do Initializers Run In The Opposite Order As Constructors? Part One
Why Do Initializers Run In The Opposite Order As Constructors? Part Two
本贴子以“现状”提供且没有任何担保,同时也没有授予任何权利
This posting is provided "AS IS" with no warranties, and confers no rights.
This posting is provided "AS IS" with no warranties, and confers no rights.

浙公网安备 33010602011771号