首页 > 编程语言 > 详细

C# 两行代码实现 延迟加载的单例模式(线程安全)

时间:2016-03-09 12:57:25      阅读:268      评论:0      收藏:0      [点我收藏+]

关键代码第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     }


测试结果:

技术分享

 

C# 两行代码实现 延迟加载的单例模式(线程安全)

原文:http://www.cnblogs.com/1zhk/p/5257340.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!