• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号
您的位置:首页 > 程序设计 >C#教程 > 解析C#中的私有构造函数和静态构造函数

解析C#中的私有构造函数和静态构造函数

作者: 字体:[增加 减小] 来源:互联网 时间:2017-05-28

通过本文主要向大家介绍了c json解析,c语言试题及解析,c值解析,c语言考试题及解析,c语言实例解析精粹等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

私有构造函数
私有构造函数是一种特殊的实例构造函数。它通常用在只包含静态成员的类中。如果类具有一个或多个私有构造函数而没有公共构造函数,则其他类(除嵌套类外)无法创建该类的实例。例如:

class NLog
{
  // Private Constructor:
  private NLog() { }

  public static double e = Math.E; //2.71828...
}

</div>

声明空构造函数可阻止自动生成默认构造函数。注意,如果您不对构造函数使用访问修饰符,则在默认情况下它仍为私有构造函数。但是,通常显式地使用 private 修饰符来清楚地表明该类不能被实例化。
当没有实例字段或实例方法(如 Math 类)时或者当调用方法以获得类的实例时,私有构造函数可用于阻止创建类的实例。如果类中的所有方法都是静态的,可考虑使整个类成为静态的。

下面是使用私有构造函数的类的示例。

public class Counter
{
  private Counter() { }
  public static int currentCount;
  public static int IncrementCount()
  {
    return ++currentCount;
  }
}

class TestCounter
{
  static void Main()
  {
    // If you uncomment the following statement, it will generate
    // an error because the constructor is inaccessible:
    // Counter aCounter = new Counter();  // Error

    Counter.currentCount = 100;
    Counter.IncrementCount();
    Console.WriteLine("New count: {0}", Counter.currentCount);

    // Keep the console window open in debug mode.
    Console.WriteLine("Press any key to exit.");
    Console.ReadKey();
  }
}

</div>

输出:

New count: 101
</div>

注意,如果您取消注释该示例中的以下语句,它将生成一个错误,因为该构造函数受其保护级别的限制而不可访问:

// Counter aCounter = new Counter();  // Error
</div>

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

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

</div>

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

  • 静态构造函数既没有访问修饰符,也没有参数。
  • 在创建第一个实例或引用任何静态成员之前,将自动调用静态构造函数来初始化类。
  • 无法直接调用静态构造函数。
  • 在程序中,用户无法控制何时执行静态构造函数。

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

静态构造函数在为非托管代码创建包装类时也很有用,此时该构造函数可以调用 LoadLibrary 方法。
如果静态构造函数引发异常,运行时将不会再次调用该构造函数,并且在程序运行所在的应用程序域的生存期内,类型将保持未初始化。
在此示例中,类 Bus 有一个静态构造函数。创建 Bus 的第一个实例(bus1)时,将调用该静态构造函数来初始化该类。输出示例验证了即使创建 Bus 的两个实例,该静态构造函数也仅运行一次,并且在实例构造函数运行之前运行。

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

</div>

输出:

   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.   
</div>

</div>
分享到:QQ空间新浪微博腾讯微博微信百度贴吧QQ好友复制网址打印

您可能想查找下面的文章:

  • 解析C#的扩展方法
  • 解析C#多线程编程中异步多线程的实现及线程池的使用
  • 解析C#设计模式编程中备忘录模式的运用
  • 解析C#设计模式编程中外观模式Facade Pattern的应用
  • 解析C#设计模式编程中的装饰者模式
  • 解析C#设计模式编程中适配器模式的实现
  • 解析C#中的分部类和分部方法
  • 解析C#中的私有构造函数和静态构造函数
  • 解析C#面向对象编程中方法(method)的使用
  • 解析C#中的常量及如何在C#编程中定义常量

相关文章

  • 2017-05-28C#实现多线程写入同一个文件的方法
  • 2017-05-28将数组中指定数量的元素移动数组后面的实现代码
  • 2017-05-28C#判断当前程序是否通过管理员运行的方法
  • 2017-05-28C#编程实现查看剪切板内容的方法
  • 2017-05-28VS2012 程序打包部署图文详解
  • 2017-05-28C#中动态显示当前系统时间的实例方法
  • 2017-05-28C# Datagridview绑定List方法代码
  • 2017-05-28C#及WPF获取本机所有字体和颜色的方法
  • 2017-05-28C#中嵌入SQLite数据库的简单方法
  • 2017-05-28C#编程实现简易图片浏览器的方法

文章分类

  • JavaScript
  • ASP.NET
  • PHP
  • 正则表达式
  • AJAX
  • JSP
  • ASP
  • Flex
  • XML
  • 编程技巧
  • Android
  • swift
  • C#教程
  • vb
  • vb.net
  • C语言
  • Java
  • Delphi
  • 易语言
  • vc/mfc
  • 嵌入式开发
  • 游戏开发
  • ios
  • 编程问答
  • 汇编语言
  • 微信小程序
  • 数据结构
  • OpenGL
  • 架构设计
  • qt
  • 微信公众号

最近更新的内容

    • C#在Unity游戏开发中进行多线程编程的方法
    • C#在RichTextBox中显示不同颜色文字的方法
    • c#判断网络连接状态的示例分享
    • 浅谈C#中简单的异常引发与处理操作
    • C#操作SQLite方法实例详解
    • C#实现Access通用访问类OleDbHelper完整实例
    • 浅谈二叉查找树的集合总结分析
    • C#根据反射和特性实现ORM映射实例分析
    • 总结C#网络编程中对于Cookie的设定要点
    • C#实现过滤html标签并保留a标签的方法

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有