先看一个静态构造函数的例子。
class Program
{
static void Main(string[] args)
{
third t= new third();
}
}
public class first
{
public first()
{
System.Console.WriteLine("I am first constructor");
}
static first()
{
System.Console.WriteLine("I am first static constructor");
}
}
public class second : first
{
public second()
{
System.Console.WriteLine("I am second constructor");
}
static second()
{
System.Console.WriteLine("I am second static constructor");
}
}
public class third : second
{
public static int number = 0;
public third()
{
System.Console.WriteLine("I am third constructor");
}
static third()
{
System.Console.WriteLine("I am third static constructor");
}
}
他的运行结果为:
I am third static constructor
I am second static constructor
I am first static constructor
I am first constructor
I am second constructor
I am third constructor
I am first constructor
I am second constructor
I am third constructor
请按任意键继续. . .
大家可以看出静态构造函数是类在构造的时候第一时间启动的函数。静态构造函数有只调用一次,即在一个进程中只能执行一次静态构造函数。
静态构造函数还有以下特性:
-
静态构造函数既没有访问修饰符,也没有参数。
-
在创建第一个实例或引用任何静态成员之前,将自动调用静态构造函数来初始化类。
-
无法直接调用静态构造函数。
-
在程序中,用户无法控制何时执行静态构造函数。
-
静态构造函数的典型用途是:当类使用日志文件时,将使用这种构造函数向日志文件中写入项。
-
静态构造函数在为非托管代码创建包装类时也很有用,此时该构造函数可以调用 LoadLibrary 方法。
以上是自己对静态构造函数的一点认识,如有不对的地方还望指正。