What is the need of private constructor in C#?

前端 未结 12 1540
鱼传尺愫
鱼传尺愫 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

    Whenever you want to prevent direct instantiation of a class from outside of it, you'll use a private constructor. For example, prior to C# 2.0 which introduced static classes, you used a private constructor to accomplish roughly the same thing:

    sealed class StaticClass {
         private StaticClass() {
         }
         public static void DoSomething() {
         }
    }
    

提交回复
热议问题