C# 静态构造函数

1、在类实例被初始化的时候执行

 

2、在类的静态成员被调用的时候执行

 

3、静态构造函数只会被执行一次,代码如下:

  static class Program
    {
        static void Main(string[] args)
        {
            Test.TestIns.Flag = Test.TestIns.Flag + 1;
            Console.WriteLine(Test.TestIns.Flag);
            Test.TestIns.Flag = Test.TestIns.Flag + 1;
            Console.WriteLine(Test.TestIns.Flag);
            Test.TestIns.Flag = Test.TestIns.Flag + 1;
            Console.WriteLine(Test.TestIns.Flag);
            Console.ReadKey();
        }
    }

    public class Test
    {
        static Test()
        {
            TestIns = new Test();
        }

        public static Test TestIns;

        public int Flag=0;
    }

说明静态构造函数只执行了一次,并将该实例初始化到了内存中.所以结果会显示成累加的情况

 

posted @ 2018-04-11 17:28  郑小超  阅读(4184)  评论(0编辑  收藏  举报