.net静态代码块执行时机

直接上代码

    public class Test
    {
        private string no;
        public static string msg;
        static Test()
        {
            Console.WriteLine("执行静态代码块");
            msg = "静态代码块";
        }
        public Test()
        {
            Console.WriteLine("执行非静态代码块");
            msg = "静态代码块";
        }
    }
        static void Main(string[] args)
        {
            Console.WriteLine("-----------------");
            Console.WriteLine(Test.msg);
            Console.WriteLine("-----------------");
            Test t2 = new Test();
            Console.WriteLine("-----------------");
            Test t3 = new Test();
            Console.ReadKey();
        }
        static void Main(string[] args)
        {
            Console.WriteLine("-----------------");
            Test t1 = new Test();
            Console.WriteLine("-----------------");
            Test t2 = new Test();
            Console.WriteLine("-----------------");
            Test t3 = new Test();
            Console.ReadKey();
        }

结果:
在这里插入图片描述
上面两段main函数的执行结果相同,都如上图所示。我们通过上面执行后我们可以看出,静态代码块的执行时机为,在第一次调用类中的静态变量前执行或在第一次实例化类时执行

发布了239 篇原创文章 · 获赞 174 · 访问量 34万+

猜你喜欢

转载自blog.csdn.net/Maybe_ch/article/details/102806017
今日推荐