zoukankan      html  css  js  c++  java
  • 私有构造函数(C# 编程指南)

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

     
    class NLog
    {
        // Private Constructor:
        private NLog() { }
    
        public static double e = Math.E;  //2.71828...
    }
    

    声明空构造函数可阻止自动生成默认构造函数。注意,如果您不对构造函数使用访问修饰符,则在默认情况下它仍为私有构造函数。但是,通常显式地使用 private 修饰符来清楚地表明该类不能被实例化。

    当没有实例字段或实例方法(如 Math 类)时或者当调用方法以获得类的实例时,私有构造函数可用于阻止创建类的实例。如果类中的所有方法都是静态的,可考虑使整个类成为静态的。有关更多信息,请参见静态类和静态类成员(C# 编程指南)

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

     
    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();
        }
    }
    // Output: New count: 101
    

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

     
    // Counter aCounter = new Counter();   // Error
  • 相关阅读:
    牡牛和牝牛
    卡特兰数 Catalan number
    Codeforces Round #633 (Div. 2)
    Codeforces Round #634 (Div. 3)
    陪审团
    线性DP
    AcWing 274. 移动服务
    Rust打印方法行号
    八.枚举与模式匹配
    七.结构体
  • 原文地址:https://www.cnblogs.com/huibin-benteng/p/5045206.html
Copyright © 2011-2022 走看看