zoukankan      html  css  js  c++  java
  • 静态构造函数

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

      

  • 相关阅读:
    正则表达式match方法和search方法
    正则表达式(基础篇1)
    动画
    重绘和重排(回流)
    数组常用的10个方法
    css3只需一招,将网站变成灰色的
    Python-类的几种调用方法
    Codeforces Global Round 8 C. Even Picture(构造)
    Codeforces Global Round 8 D. AND, OR and square sum(位运算)
    Codeforces Round #650 (Div. 3) C. Social Distance
  • 原文地址:https://www.cnblogs.com/xiao9426926/p/5908157.html
Copyright © 2011-2022 走看看