What is the need of private constructor in C#?

前端 未结 12 1501
鱼传尺愫
鱼传尺愫 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 21:55

    When you want to prevent the users of your class from instantiating the class directly. Some common cases are:

    • Classes containing only static methods
    • Singletons
    0 讨论(0)
  • 2020-12-13 21:57

    Basically you use private constructors when you are following a singleton design pattern. In this case, you have a static method defined inside the class that internally calls the private constructor.

    So to create the instance of the class for the first time, the user calls the classname.static_method_name. In this method, since the class's object doesn't yet exist, the static method internally calls the private constructor and returns the class's instance.

    If the class's instance already exists, then the static method simply returns the instance to the calling method.

    0 讨论(0)
  • 2020-12-13 21:58

    If you know some design pattern, it's obvious: a class could create a new instance of itself internally, and not let others do it. An example in Java (I don't know C# well enough, sorry) with a singleton-class:

    class Meh 
    {
      private Meh() { }
      private static Meh theMeh = new Meh();
      public static Meh getInstance() { return theMeh; }
    }
    
    0 讨论(0)
  • 2020-12-13 21:59

    I can can recall few usages for it:

    • You could use it from a static factory method inside the same class
    • You could do some common work inside it and then call it from other contructure
    • You could use it to prevent the runtime from adding an empty contructure automatically
    • It could be used (although private) from some mocking and ORM tools (like nhibernate)
    0 讨论(0)
  • 2020-12-13 22:00

    And of course you can use private constructor to prevent subclassing.

    0 讨论(0)
  • 2020-12-13 22:01

    For example when you provide factory methods to control instantiation...

    public class Test(){
    
      private Test(){
      }
    
      void DoSomething(){
        // instance method
      }
    
      public static Test CreateCoolTest(){
        return new Test();
      }
    }
    
    0 讨论(0)
提交回复
热议问题