Prevent usage of default constructor

后端 未结 5 499
-上瘾入骨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-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.

提交回复
热议问题