静态构造函数(C# 编程指南)
静态构造函数用于初始化任何静态数据,或用于执行仅需执行一次的特定操作。在创建第一个实例或引用任何静态成员之前,将自动调用静态构造函数。
1
class SimpleClass
2
{
3
// Static constructor
4
static SimpleClass()
5
{
6
//
7
}
8
}
class SimpleClass2
{3
// Static constructor4
static SimpleClass()5
{6
//
7
}8
}静态构造函数具有以下特点:
-
静态构造函数既没有访问修饰符,也没有参数。
-
在创建第一个实例或引用任何静态成员之前,将自动调用静态构造函数来初始化类。
-
无法直接调用静态构造函数。
-
在程序中,用户无法控制何时执行静态构造函数。
-
静态构造函数的典型用途是:当类使用日志文件时,将使用这种构造函数向日志文件中写入项。
-
静态构造函数在为非托管代码创建包装类时也很有用,此时该构造函数可以调用 LoadLibrary 方法。
在此示例中,类 Bus 有一个静态构造函数和一个静态成员 Drive()。当调用 Drive() 时,将调用静态构造函数来初始化类。
1
public class Bus
2
{
3
// Static constructor:
4
static Bus()
5
{
6
System.Console.WriteLine("The static constructor invoked.");
7
}
8
9
public static void Drive()
10
{
11
System.Console.WriteLine("The Drive method invoked.");
12
}
13
}
14
15
class TestBus
16
{
17
static void Main()
18
{
19
Bus.Drive();
20
}
21
}
public class Bus2
{3
// Static constructor:4
static Bus()5
{6
System.Console.WriteLine("The static constructor invoked.");7
}8

9
public static void Drive()10
{11
System.Console.WriteLine("The Drive method invoked.");12
}13
}14

15
class TestBus16
{17
static void Main()18
{19
Bus.Drive();20
}21
}输出
The static constructor invoked.
The Drive method invoked.


浙公网安备 33010602011771号