首页 > Windows开发 > 详细

C# 单例3种写法

时间:2015-08-27 15:00:43      阅读:178      评论:0      收藏:0      [点我收藏+]
public class Singleton { private static Singleton _instance = null; private Singleton(){} public static Singleton CreateInstance() { if(_instance == null) { _instance = new Singleton(); } return _instance; } } 第二种考虑了线程安全,不过有点烦,但绝对是正规写法,经典的一叉 public class Singleton { private volatile static Singleton _instance = null; private static readonly object lockHelper = new object(); private Singleton(){} public static Singleton CreateInstance() { if(_instance == null) { lock(lockHelper) { if(_instance == null) _instance = new Singleton(); } } return _instance; } } 第三种可能是C#这样的高级语言特有的,实在懒得出奇 public class Singleton { private Singleton(){} public static readonly Singleton instance = new Singleton(); } 哦,shit!

C# 单例3种写法

原文:http://www.cnblogs.com/dullbaby/p/4763097.html

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