行下图中的C#代码,输出是什么?
namespace StaticConstructor
{
classA
{
public A(string text)
{
Console.WriteLine(text);
}
}
classB
{
staticA a1 = newA("a1");
A a2 = newA("a2");
static B()
{
a1 = newA("a3");
}
public B()
{
a2 = newA("a4");
}
}
classProgram
{
staticvoid Main(string[] args)
{
B b = newB();
}
}
}
答案:打印出四行,分别是a1、a3、a2、a4。
在调用类型B的代码之前先执行B的静态构造函数。静态函数先初始化类型的静态变量,再执行静态函数内的语句。因此先打印a1再打印a3。接下来执行B b = new B(),即调用B的普通构造函数。构造函数先初始化成员变量,在执行函数体内的语句,因此先后打印出a2、a4。