在博客园中看到别人对静态构造函数的解释。自己也不是很明白顺便学习一下

using System;
using System.Collections.Generic;
using System.Text;

namespace ConsoleApplication1
{

    public class Test
    { 
        static Test()
        {
            Console.WriteLine("我是静态构造方法");
        }

        public Test()
        {
            Console.WriteLine("我是初始化方法");
        }
        public static void Write()
        {
            Console.WriteLine("我准备写东西在屏幕上了");
            Console.WriteLine("Hello World!!!");

        }
    }
    
    public class Program
    {
        #region 调用静态方法 执行静态构造方法
        //static void Main(string[] args)
        //{
        //    Test.Write();
        //    Console.ReadKey();
        //}
        #endregion
        

        #region 创建第一个Test类时执行静态构造方法
        static void Main(string[] args)
        {
            Test tst = new Test();
            Console.ReadKey();
        }
        #endregion
    }


}


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

 
                    
            
                

相关文章:

  • 2021-09-13
  • 2021-10-26
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-07-21
相关资源
相似解决方案