为什么 C# 中的单例类总是密封的?

来源:这里教程网 时间:2026-02-21 16:18:01 作者:

为什么 c# 中的单例类总是密封的?

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 {
   }
}

相关推荐