Why do we need a private constructor?

后端 未结 10 534
一整个雨季
一整个雨季 2020-11-30 18:20

If a class has a private constructor then it can\'t be instantiated. So, if I don\'t want my class to be instantiated and still use it, then I can make it static.

Wh

相关标签:
10条回答
  • 2020-11-30 18:50

    You can use it to force a singleton instance or create a factory class.

    A static method can call the private constructor to create a new instance of that class.

    For example a singleton instance:

    public class Foo
    {
    
      private Foo (){}
    
      private Foo FooInstance {get;set;}
    
      public static Foo GetFooInstance ()
      {
        if(FooInstance == null){
          FooInstance = new Foo();
        }
    
        return FooInstance;
      }
    
    }
    

    This allows only one instance of the class to be created.

    0 讨论(0)
  • 2020-11-30 18:50

    If you want to create a factory for a class, you can use a private constructur, and add some static "factory" methods to the class itself to create the class.

    An example for this is the Graphics class, with the From* methods.

    0 讨论(0)
  • 2020-11-30 18:56

    Well if your only objective is that you don't want it to be instantiated, then making it static is sufficient.

    If, otoh, you simply don't want it to be instaniated frm outside the class, (maybe you only want users to get one by using a static factory on the class) - then you need a private ctor to allow those publicly accessible static factories to instantiate it.

    Historically, remember that making a class static has not always been around... Making the ctor private was a way to make it not-instantiatable (is this a word? ) before the static keyword could be applied to a class...

    0 讨论(0)
  • 2020-11-30 18:56

    Private constructors is a special instance constructor. and are used in some cases where we create a class which only have static members, so creating instance of this class is useless, and that is where private constructor comes into play.

    If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of this class.

    example:

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

    The declaration of the empty constructor prevents the automatic generation of a parameter less constructor.

    If you do not use an access modifier with the constructor it will still be private by default. Read more: https://qawithexperts.com/tutorial/c-sharp/32/private-constructor-in-c-sharp

    0 讨论(0)
提交回复
热议问题