关键代码第4,5行。
很简单的原理不解释:readonly + Lazy(.Net 4.0 + 的新特性)
1 public class LazySingleton 2 { 3 //Lazy singleton 4 private LazySingleton() { } 5 public static readonly Lazy<LazySingleton> instance = new Lazy<LazySingleton>(() => { return new LazySingleton(); }); 6 7 //not lazy Singleton 8 //public static readonly LazySingleton instance = new LazySingleton(); 9 10 public String Name { get; set; } 11 } 12 13 public class LazySingletonDemo 14 { 15 public static void Execute() 16 { 17 18 if (!LazySingleton.instance.IsValueCreated) 19 Console.WriteLine("LazySingleton is not initialized"); 20 21 LazySingleton.instance.Value.Name = "HK"; 22 23 Console.WriteLine(LazySingleton.instance.Value.Name); 24 } 25 }
测试结果:
时间: 2024-10-05 04:47:02