using System; using System.Collections.Generic; using System.Text; namespace 单件模式 { class Program { //定义一个密封类,防止继承 public sealed class President { //静态只读的字段,起到全局的作用,在这里创建类 public static readonly President myPresident = new President(); //将构造器设为私有,避免用new去创建实例 private President() { } } static void Main(string[] args) { //调用时候定义后直接用类的字段赋值,这里就得到类的实例 President p = President.myPresident; Console.WriteLine(p.GetType()); President p1 = President.myPresident; if (p.Equals(p1)) { Console.WriteLine("同一个实例"); } Console.Read(); } } }