原文地址:http://www.csharp411.com/c-object-initialization/
當構造一個C#對象時,理解對象的作用域和構造器被初始化的序列是很重要的
Derived static fIElds
Derived static constructor
Derived instance fIElds
Base static fIElds
Base static constructor
Base instance fIElds
Base instance constructor
Derived instance constructor
示例
下面的是一個C#控制台程序的例子,這個例子演示了對象初始化的次序
這個程序創建基對象的派生對象,包含了靜態化和實例化構造器以及作用域,兩個作用域"Field1"和"Field2"在他們的定義裡被初始化,然而 "FIEld3"在構造器裡被初始化.同時也包含了一個證明為什麼不能從構造器裡調用虛方法的虛方法.當每個作用域和構造器被初始化時就會寫入控制台,因此你可以看到初始化的序列
using System;
namespace ObjectInit
{
class Program
{
static void Main( string[] args )
{
Derived d = new Derived();
Console.ReadLine();
}
}
class Base
{
public Base()
{
Console.WriteLine( "Base.Instance.Constructor" );
this.m_Field3 = new Tracker( "Base.Instance.FIEld3″ );
this.Virtual();
}
static Base()
{
Console.WriteLine( "Base.Static.Constructor" );
}
private Tracker m_Field1 = new Tracker( "Base.Instance.FIEld1″ );
private Tracker m_Field2 = new Tracker( "Base.Instance.FIEld2″ );
private Tracker m_FIEld3;
static private Tracker s_Field1 = new Tracker( "Base.Static.FIEld1″ );
static private Tracker s_Field2 = new Tracker( "Base.Static.FIEld2″ );
virtual public void Virtual()
{
Console.WriteLine( "Base.Instance.Virtual" );
}
}
class Derived : Base
{
public Derived()
{
Console.WriteLine( "Derived.Instance.Constructor" );
this.m_Field3 = new Tracker( "Derived.Instance.FIEld3″ );
}
static Derived()
{
Console.WriteLine( "Derived.Static.Constructor" );
}
private Tracker m_Field1 = new Tracker( "Derived.Instance.FIEld1″ );
private Tracker m_Field2 = new Tracker( "Derived.Instance.FIEld2″ );
private Tracker m_FIEld3;
static private Tracker s_Field1 = new Tracker( "Derived.Static.FIEld1″ );
static private Tracker s_Field2 = new Tracker( "Derived.Static.FIEld2″ );
override public void Virtual()
{
Console.WriteLine( "Derived.Instance.Virtual" );
}
}
class Tracker
{
public Tracker( string text )
{
Console.WriteLine( text );
}
}
}