对c#中的静态构造函数的一点理解

先看一个静态构造函数的例子。

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 方法。

以上是自己对静态构造函数的一点认识,如有不对的地方还望指正。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值