sealed关键字表示无法从该类继承。将构造函数声明为私有意味着无法创建该类的实例。
您可以拥有一个带有私有构造函数的基类,但是仍然继承自该基类,定义一些公共构造函数,并有效地实例化该基类。
构造函数不会被继承(因此,派生类不会仅因为基类就拥有所有私有构造函数),并且派生类始终会首先调用基类构造函数。
将类标记为密封可防止某人琐碎地处理您精心构造的单例类,因为它使某人无法从该类继承。
static class Program { static void Main(string[] args){ Singleton fromStudent = Singleton.GetInstance; fromStudent.PrintDetails("From Student"); Singleton fromEmployee = Singleton.GetInstance; fromEmployee.PrintDetails("From Employee"); Console.WriteLine("-------------------------------------"); Singleton.DerivedSingleton derivedObj = new Singleton.DerivedSingleton(); derivedObj.PrintDetails("From Derived"); Console.ReadLine(); } } public class Singleton { private static int counter = 0; private static object obj = new object(); private Singleton() { counter++; Console.WriteLine("Counter Value " + counter.ToString()); } private static Singleton instance = null; public static Singleton GetInstance{ get { if (instance == null) instance = new Singleton(); return instance; } } public void PrintDetails(string message){ Console.WriteLine(message); } public class DerivedSingleton : Singleton { } }