静态构造函数用于初始化任何静态数据,或用于执行仅需执行一次的特定操作。在创建第一个实例或引用任何静态成员之前,将自动调用静态构造函数

静态构造函数具有以下特点:
  • 静态构造函数既没有访问修饰符,也没有参数。
  • 在创建第一个实例或引用任何静态成员之前,将自动调用静态构造函数来初始化
  • 无法直接调用静态构造函数。
  • 在程序中,用户无法控制何时执行静态构造函数。
  • 静态构造函数的典型用途是:当类使用日志文件时,将使用这种构造函数向日志文件中写入项。
  • 静态构造函数在为非托管代码创建包装类时也很有用,此时该构造函数可以调用  LoadLibrary 方法。

    InBlock.gif public class Bus
    InBlock.gif{
    InBlock.gif         // Static constructor:
    InBlock.gif         static Bus()
    InBlock.gif        {
    InBlock.gif                System.Console.WriteLine( "The static constructor invoked.");
    InBlock.gif        }
    InBlock.gif
             public static void Drive()
    InBlock.gif        {
    InBlock.gif                System.Console.WriteLine( "The Drive method invoked.");
    InBlock.gif        }
    InBlock.gif}
    InBlock.gif
    class TestBus
    InBlock.gif{
    InBlock.gif         static void Main()
    InBlock.gif        {
    InBlock.gif                Bus.Drive();
    InBlock.gif        }
    InBlock.gif}
    输出:
    The static constructor invoked.
    The Drive method invoked.