码迷,mamicode.com
首页 > Windows程序 > 详细

C# 静态构造函数

时间:2018-04-11 18:12:33      阅读:210      评论:0      收藏:0      [点我收藏+]

标签:函数   ons   bsp   ati   line   color   key   结果   str   

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;
    }

技术分享图片

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

 

C# 静态构造函数

标签:函数   ons   bsp   ati   line   color   key   结果   str   

原文地址:https://www.cnblogs.com/GreenLeaves/p/8797050.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!