服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - 解析C#中的私有构造函数和静态构造函数

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

2021-11-09 13:10C#教程网 C#

这篇文章主要介绍了C#中的私有构造函数和静态构造函数,是C#入门学习中的基础知识,需要的朋友可以参考下

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

?
1
2
3
4
5
6
7
class NLog
{
  // Private Constructor:
  private NLog() { }
 
  public static double e = Math.E; //2.71828...
}

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

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

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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();
  }
}

输出:

?
1
New count: 101

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

?
1
// Counter aCounter = new Counter();  // Error

 

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

?
1
2
3
4
5
6
7
8
9
10
11
12
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 的两个实例,该静态构造函数也仅运行一次,并且在实例构造函数运行之前运行。

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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();
  }
}

输出:

?
1
2
3
4
5
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.  

延伸 · 阅读

精彩推荐
  • C#C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    这篇文章主要介绍了C#实现的文件操作封装类,结合完整实例形式分析了C#封装文件的删除,移动,复制,重命名等操作相关实现技巧,需要的朋友可以参考下...

    Rising_Sun3892021-12-28
  • C#C#直线的最小二乘法线性回归运算实例

    C#直线的最小二乘法线性回归运算实例

    这篇文章主要介绍了C#直线的最小二乘法线性回归运算方法,实例分析了给定一组点,用最小二乘法进行线性回归运算的实现技巧,具有一定参考借鉴价值,需要...

    北风其凉8912021-10-18
  • C#聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题,新手速来围观,一个通俗易懂的例子帮助大家更好的理解C#接口问题,感兴趣的小伙伴们可以参考一下...

    zenkey7072021-12-03
  • C#浅谈C# winForm 窗体闪烁的问题

    浅谈C# winForm 窗体闪烁的问题

    下面小编就为大家带来一篇浅谈C# winForm 窗体闪烁的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    C#教程网7962021-12-21
  • C#Unity3D UGUI实现缩放循环拖动卡牌展示效果

    Unity3D UGUI实现缩放循环拖动卡牌展示效果

    这篇文章主要为大家详细介绍了Unity3D UGUI实现缩放循环拖动展示卡牌效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参...

    诗远3662022-03-11
  • C#c#学习之30分钟学会XAML

    c#学习之30分钟学会XAML

    一个界面程序的核心,无疑就是界面和后台代码,而xaml就是微软为构建应用程序界面而创建的一种描述性语言,也就是说,这东西是搞界面的...

    C#教程网8812021-12-10
  • C#C#基础之泛型

    C#基础之泛型

    泛型是 2.0 版 C# 语言和公共语言运行库 (CLR) 中的一个新功能。接下来通过本文给大家介绍c#基础之泛型,感兴趣的朋友一起学习吧...

    方小白7732021-12-03
  • C#C# 后台处理图片的几种方法

    C# 后台处理图片的几种方法

    本篇文章主要介绍了C# 后台处理图片的几种方法,非常具有实用价值,需要的朋友可以参考下。...

    IT小伙儿10162021-12-08