保证一个类只有一个实例,并提供一个全局访问点。
public class Singleton { // 私有静态实例 private static readonly Lazy<Singleton> _instance = new Lazy<Singleton>(() => new Singleton()); // 私有构造函数,防止外部实例化 private Singleton() { } // 公共访问属性 public static Singleton Instance => _instance.Value; // 测试方法 public void ShowMessage() => Console.WriteLine("单例模式测试,实例哈希码: " + GetHashCode()); } // 调用示例 public static void TestSingleton() { var s1 = Singleton.Instance; var s2 = Singleton.Instance; s1.ShowMessage(); s2.ShowMessage(); Console.WriteLine("是否为同一实例: " + (s1 == s2)); // True }