这是一个有效的,懒惰的,线程安全的Singleton实现的C#? [英] Is this a valid, lazy, thread-safe Singleton implementation for C#?
问题描述
我实现了一个Singleton模式是这样的:
I implemented a Singleton pattern like this:
public sealed class MyClass {
...
public static MyClass Instance {
get { return SingletonHolder.instance; }
}
...
static class SingletonHolder {
public static MyClass instance = new MyClass ();
}
}
从周围的Googling为C#辛格尔顿实现,这不是' ŧ看起来这是做事情在C#中的常用方法。我发现了一个类似的实现,但SingletonHolder类是不是静态的,并包括一个明确的(空)静态构造函数。
From Googling around for C# Singleton implementations, it doesn't seem like this is a common way to do things in C#. I found one similar implementation, but the SingletonHolder class wasn't static, and included an explicit (empty) static constructor.
这是一个有效的,懒惰的,线程安全方式来实现Singleton模式? ?或者是有什么我失踪
Is this a valid, lazy, thread-safe way to implement the Singleton pattern? Or is there something I'm missing?
推荐答案
乔恩斯基特写的的article 有关实现在C#Singleton模式
Jon Skeet has written an article about implementing the Singleton pattern in 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();
}
}
特别是,您必须显式声明构造通知即使它是空的,以使其私有的。
Notice in particular that you have to explicitly declare a constructor even if it is empty in order to make it private.
这篇关于这是一个有效的,懒惰的,线程安全的Singleton实现的C#?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!