http://www.cnblogs.com/teamleader/archive/2011/01/25/1944810.html
你可能不知道的对象实例化顺序
猜猜下面这段代码的输入,我预计90%以上的人给不出正确的答案
void Main()
{
InitSeqBase x = new InitSeqChild();
}
public class InitSeqBase
{
public static Nothing _SField = new Nothing("base static field initializer");
static InitSeqBase()
{
Console.WriteLine("base static constructor");
}
public Nothing InsField = new Nothing("base Instance field initializer");
public InitSeqBase()
{
Console.WriteLine("base Instance constructor");
}
}
public class InitSeqChild : InitSeqBase
{
public static Nothing _SField = new Nothing("child static field initializer");
static InitSeqChild()
{
Console.WriteLine("child static constructor");
}
public Nothing InsField = new Nothing("child Instance field initializer");
public InitSeqChild()
{
Console.WriteLine("child Instance constructor");
}
}
public class Nothing
{
public Nothing(string s)
{
Console.WriteLine(s);
}
}
{
InitSeqBase x = new InitSeqChild();
}
public class InitSeqBase
{
public static Nothing _SField = new Nothing("base static field initializer");
static InitSeqBase()
{
Console.WriteLine("base static constructor");
}
public Nothing InsField = new Nothing("base Instance field initializer");
public InitSeqBase()
{
Console.WriteLine("base Instance constructor");
}
}
public class InitSeqChild : InitSeqBase
{
public static Nothing _SField = new Nothing("child static field initializer");
static InitSeqChild()
{
Console.WriteLine("child static constructor");
}
public Nothing InsField = new Nothing("child Instance field initializer");
public InitSeqChild()
{
Console.WriteLine("child Instance constructor");
}
}
public class Nothing
{
public Nothing(string s)
{
Console.WriteLine(s);
}
}
答案在此(选中后可见,白色字体):
child static field initializer
child static constructor
child Instance field initializer
base static field initializer
base static constructor
base Instance field initializer
base Instance constructor
child Instance constructor
谢谢参与!