简体   繁体   English

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

[英]Is this Singleton implementation correct and thread-safe?

Is this singleton implementation correct and thread-safe? 这个单例实现是否正确且是线程安全的?

class Class
{
    public static readonly Class Instance;

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

    private Class() {}
}

Technically, your version should work. 从技术上讲,您的版本应该可行。 However, I would not recommend exposing a public field within your Singleton class, and prefer using a Property (with a getter only). 但是,我不建议在Singleton类中公开公共字段,而是更喜欢使用Property(仅使用getter)。 This will help future-proof your API if you need to make changes later. 如果您以后需要进行更改,这将有助于您的API未来发展。 I also recommend sealing any singleton implementation, as subclassing a singleton class is almost always a bad idea and problematic. 我还建议密封任何单例实现,因为子类化单例类几乎总是一个坏主意并且有问题。

I would, personally, use the following in C#, if you're targetting .NET 3.5 or earlier: 如果您的目标是.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() { }
}

If you're using .NET 4, you can make this even easier for yourself via Lazy<T> : 如果你使用的是.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; } }
}

The .NET 4 version also has the advantage of being fully lazy - even if your Singleton class has other static methods which are used prior to the access of the "Instance" property. .NET 4版本还具有完全延迟的优点 - 即使您的Singleton类具有在访问“Instance”属性之前使用的其他静态方法。 You can do a fully-lazy .NET 3.5- version, as well, by using a private, nested class. 您也可以使用私有的嵌套类来完成一个完全懒惰的.NET 3.5版本。 Jon Skeet demonstrated this on his blog . Jon Skeet在他的博客上证明了这一点

Yes. 是。 I would also make the class ' sealed ' to avoid any future confusion. 我也会让课程“ sealed ”以避免将来出现任何混淆。

Good discussion of how to do that is here: 关于如何做到这一点的好讨论在这里:

http://www.yoda.arachsys.com/csharp/singleton.html http://www.yoda.arachsys.com/csharp/singleton.html

您应该在变量声明中进行初始化:

public static readonly Class Instance = new Class();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM