这个Singleton实现是否正确并且是线程安全的?

Fer*_*dil 7 c# singleton multithreading

这个单例实现是否正确且是线程安全的?

class Class
{
    public static readonly Class Instance;

    static Class()
    {
        Instance = new Class();
    }

    private Class() {}
}
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 12

从技术上讲,您的版本应该可行.但是,我不建议在Singleton类中公开公共字段,而是更喜欢使用Property(仅使用getter).如果您以后需要进行更改,这将有助于您的API未来发展.我还建议密封任何单例实现,因为子类化单例类几乎总是一个坏主意并且有问题.

如果您的目标是.NET 3.5或更早版本,我个人会在C#中使用以下内容:

public sealed class Singleton
{
    static readonly Singleton instance = new Singleton();

    public static Singleton Instance
    {
        get
        {
            return instance;
        }
    }

    static Singleton() { }
    private Singleton() { }
}
Run Code Online (Sandbox Code Playgroud)

如果您使用的是.NET 4,则可以通过Lazy<T>以下方式让自己更轻松:

public sealed class Singleton
{
     private static readonly Lazy<Singleton> instance = new Lazy<Singleton>( () => new Singleton() );
     private Singleton() {}
     public static Singleton Instance { get { return instance.Value; } }
}
Run Code Online (Sandbox Code Playgroud)

.NET 4版本还具有完全延迟的优点 - 即使您的Singleton类具有在访问"Instance"属性之前使用的其他静态方法.您也可以使用私有的嵌套类来完成一个完全懒惰的.NET 3.5版本. Jon Skeet在他的博客上证明了这一点.