An obvious singleton implementation for .NET?

后端 未结 7 1137
轻奢々
轻奢々 2020-12-02 11:38

I was thinking about the classic issue of lazy singleton initialization - the whole matter of the inefficiency of:

if (instance == null)
{
    instance = new         


        
7条回答
  •  渐次进展
    2020-12-02 12:01

    This is the canonical, thread safe, lazy Singleton pattern in C#:

    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();
        }
    }
    

提交回复
热议问题