博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
静态构造函数(C# 编程指南)
阅读量:7118 次
发布时间:2019-06-28

本文共 3284 字,大约阅读时间需要 10 分钟。

Visual Studio 2010
 
 
 
此主题尚未评级 
 

 

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

C#
 
class SimpleClass{    // Static variable that must be initialized at run time.    static readonly long baseline;    // Static constructor is called at most one time, before any    // instance constructor is invoked or member is accessed.    static SimpleClass()    {        baseline = DateTime.Now.Ticks;    }}

静态构造函数具有以下特点:

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

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

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

  • 在程序中,用户无法控制何时执行静态构造函数。

  • 静态构造函数的典型用途是:当类使用日志文件时,将使用这种构造函数向日志文件中写入项。

  • 静态构造函数在为非托管代码创建包装类时也很有用,此时该构造函数可以调用 LoadLibrary 方法。

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


在此示例中,类 Bus 有一个静态构造函数。 创建 Bus 的第一个实例(bus1)时,将调用该静态构造函数来初始化该类。 输出示例验证了即使创建 Bus 的两个实例,该静态构造函数也仅运行一次,并且在实例构造函数运行之前运行。

C#
 
public class Bus    {        // Static variable used by all Bus instances.        // Represents the time the first bus of the day starts its route.        protected static readonly DateTime globalStartTime;        // Property for the number of each bus.        protected int RouteNumber { get; set; }        // Static constructor to initialize the static variable.        // It is invoked before the first instance constructor is run.        static Bus()        {            globalStartTime = DateTime.Now;            // The following statement produces the first line of output,             // and the line occurs only once.            Console.WriteLine("Static constructor sets global start time to {0}",                globalStartTime.ToLongTimeString());        }        // Instance constructor.        public Bus(int routeNum)        {            RouteNumber = routeNum;            Console.WriteLine("Bus #{0} is created.", RouteNumber);        }        // Instance method.        public void Drive()        {            TimeSpan elapsedTime = DateTime.Now - globalStartTime;            // For demonstration purposes we treat milliseconds as minutes to simulate            // actual bus times. Do not do this in your actual bus schedule program!            Console.WriteLine("{0} is starting its route {1:N2} minutes after global start time {2}.",                                    this.RouteNumber,                                    elapsedTime.TotalMilliseconds,                                    globalStartTime.ToShortTimeString());        }    }    class TestBus    {        static void Main()        {            // The creation of this instance activates the static constructor.            Bus bus1 = new Bus(71);            // Create a second bus.            Bus bus2 = new Bus(72);            // Send bus1 on its way.            bus1.Drive();            // Wait for bus2 to warm up.            System.Threading.Thread.Sleep(25);            // Send bus2 on its way.            bus2.Drive();            // Keep the console window open in debug mode.            System.Console.WriteLine("Press any key to exit.");            System.Console.ReadKey();        }    }    /* Sample output:        Static constructor sets global start time to 3:57:08 PM.        Bus #71 is created.        Bus #72 is created.        71 is starting its route 6.00 minutes after global start time 3:57 PM.        72 is starting its route 31.00 minutes after global start time 3:57 PM.         */

参考

概念

转载地址:http://ociel.baihongyu.com/

你可能感兴趣的文章
基于Redis的分布式锁的简单实现
查看>>
Python笔记---错误笔记
查看>>
Linux杀毒软件ClamAV初次体验
查看>>
phpmyadmin设置自动登录和取消自动登录
查看>>
使用canvas制作一个移动端画板
查看>>
linux shell if 参数
查看>>
TRIZ的成功案例
查看>>
Centos启用rz/sz命令
查看>>
微信公众号开发之创建菜单栏代码示例(php)
查看>>
【转】C盘不能扩展卷怎么回事 C盘扩展卷灰色的解决办法
查看>>
iOS性能优化专题
查看>>
在Linux中查看正在运行哪些process,杀掉一批名字相同的process
查看>>
快学Scala习题解答—第四章 映射和元组
查看>>
JQuery的ajaxFileUpload的使用
查看>>
dva/dynamic
查看>>
Intelli IDEA快捷键(配合IdeaVim)
查看>>
Redis简单案例(二) 网站最近的访问用户
查看>>
数据库历险记(三) | 缓存框架的连环炮
查看>>
CSS3属性transform详解之(旋转:rotate,缩放:scale,倾斜:skew,移动:translate)
查看>>
Eclipse创建一个JAVA WEB项目
查看>>