静态构造函数

1. 静态构造函数用于初始化静态数据,或用于执行仅需执行一次的特殊操作。

2. 静态构造函数既没有访问修饰符,也没有参数。

3. 在创建第一个实例或引用任何静态成员之前,将自动调用静态构造函数来初始化类。

4. 无法直接调用静态构造函数。

5. 如果静态构造函数引发异常,运行时将不会再次调用该构造函数,并且在程序运行所在的应用程序域的生存期内,类型将保持未初始化。

    class Program
    {
        static void Main(string[] args)
        {
            // 在bus1实例化后调用静态构造函数,只调用一次
            Bus bus1 = new Bus(71);
            Bus bus2 = new Bus(72);
            bus1.Drive();
            System.Threading.Thread.Sleep(3600);
            bus2.Drive();
            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
    }
    public class Bus
    {
        protected static readonly DateTime globalStartTime;
        protected int RouteNumber { get; set; }
        static Bus ()
        {
            globalStartTime = DateTime.Now;
            Console.WriteLine("static constructor sets global start time to {0}", globalStartTime.ToLongTimeString());
        }
        public Bus (int routeNum)
        {
            RouteNumber = routeNum;
            Console.WriteLine("Bus #{0} is created", RouteNumber);
        }
        public void Drive()
        {
            TimeSpan elapsedTime = DateTime.Now - globalStartTime;
            Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}", this.RouteNumber, elapsedTime.TotalMilliseconds, globalStartTime.ToLongTimeString());
        }
    }

  

posted @ 2016-09-26 10:20  HepburnXiao  阅读(430)  评论(0编辑  收藏  举报