What is the need of private constructor in C#?

前端 未结 12 1554
鱼传尺愫
鱼传尺愫 2020-12-13 21:32

What is the need of private constructor in C#? I got it as a question for a C# test.

12条回答
  •  难免孤独
    2020-12-13 22:06

    Private constructors are used to prevent the creation of instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the entire class static. For more information see Static Classes and Static Class Members.

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

    The following is an example of a class using a private constructor.

    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();
            System.Console.WriteLine("New count: {0}", Counter.currentCount);
        }
    }
    

提交回复
热议问题