我实现了这样的单例模式:
public sealed class MyClass {
...
public static MyClass Instance {
get { return SingletonHolder.instance; }
}
...
static class SingletonHolder {
public static MyClass instance = new MyClass ();
}
}
通过 Google 搜索 C# 单例实现,这似乎不是在 C# 中执行操作的常见方法。我发现了一个类似的实现,但 SingletonHolder 类不是静态的,并且包含一个显式(空)静态构造函数。
这是实现单例模式的有效、惰性、线程安全的方法吗?或者我缺少什么?
乔恩·斯基特写过一篇article http://www.yoda.arachsys.com/csharp/singleton.html关于在 C# 中实现单例模式。
惰性实现是版本 5:
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
特别注意,即使构造函数为空,您也必须显式声明它才能将其设为私有。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)