Prevent usage of default constructor

后端 未结 5 488
-上瘾入骨i
-上瘾入骨i 2020-12-13 23:30

Is there a way to prevent the usage of the default constructor?

All I can think of is throwing an exception, but I would like something that causes a compile time er

相关标签:
5条回答
  • 2020-12-13 23:42

    You can just make it private:

    private MyClass()
    {
    }
    

    Alternatively (if you didn't know already) if you just declare a constructor with parameters, the default one isn't added by the compiler, e.g.

    private MyClass(string myParameter)
    {
        //Can't call new MyClass() anymore
    }
    
    0 讨论(0)
  • 2020-12-13 23:46

    Make it private.

    So,

    class SomeClass
    {
        private SomeClass()
        {
        }
    
        public SomeClass(int SomeParam)
        {
        }
    }
    
    0 讨论(0)
  • 2020-12-13 23:47

    Aside from other answers, you can read following text, for more info on Singleton pattern, and some examples. Singleton pattern relies on constructor being private.

    http://www.yoda.arachsys.com/csharp/singleton.html

    0 讨论(0)
  • 2020-12-13 23:53
    • If everything in the class is static, consider making it a static class. That way, you won't get a constructor at all.
    • If you want a parameterless constructor but you don't want it to be public, declare it explicitly and make it private (or internal etc)
    • If you don't want a parameterless constructor but do want constructors with parameters, then just declare the parameterized constructor - the default constructor won't be generated for you

    I think that should cover all bases...

    0 讨论(0)
  • 2020-12-14 00:03

    One thing to mention that others have not. The default constructor should still be able to set up the default implementation bits, to avoid reuse. This is not a problem if it is private, as you can still chain down to a private constructor. You just make it unavailable to outside sources.

    private MyClass()
    {
    }
    
    public MyClass(string something) : this()
    {
    }
    

    That solves the problem. Note, however, that protected may actually be a preferred implementation if the class is not sealed.

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