子类会执行父类的静态构造函数,不过是在执行完自己的静态构造函数之后。验证代码:
class A
{
static A()
{
Console.WriteLine("A的静态构造函数");
}
}
class B:A
{
static B()
{
Console.WriteLine("B的静态构造函数");
}
} class Program
{
static void Main(string[] args)
{
B b= new B();
Console.Read();
}
}
{
static A()
{
Console.WriteLine("A的静态构造函数");
}
}
class B:A
{
static B()
{
Console.WriteLine("B的静态构造函数");
}
} class Program
{
static void Main(string[] args)
{
B b= new B();
Console.Read();
}
}
结果:
这个例子不好,换一个:
class A
{
protected static string stra;
protected static string strb;
static A()
{
stra = "A的静态构造函数";
}
public static void show()
{
Console.WriteLine(stra);
Console.WriteLine(strb);
}
}
class B : A
{ static B()
{
A.strb = "B的静态构造函数";
}
{
static void Main(string[] args)
{
B b = new B();
B.show();
Console.Read();
}
}
{
protected static string stra;
protected static string strb;
static A()
{
stra = "A的静态构造函数";
}
public static void show()
{
Console.WriteLine(stra);
Console.WriteLine(strb);
}
}
class B : A
{ static B()
{
A.strb = "B的静态构造函数";
}
}
class Program{
static void Main(string[] args)
{
B b = new B();
B.show();
Console.Read();
}
}
执行结果是一样的:
但是如果把 B b = new B();这一句注释掉,结果就变成了这样:
这一句话的差别成了我的郁闷之源。我在一个类中用到了一个静态字段,这个字段供一个静态方法调用,他的值需要在子类中确定,于是我就在子类的静态构造函数中给他赋值。结果在调用时老是报错,花了几个小时没有找到原因。所以就把问题简化,写了这么个简单的类,改来改去,又花了N多时间才找到问题所在~基础知识不牢害死人啊!~
为避免重复犯错,故志之。