An obvious singleton implementation for .NET?

后端 未结 7 1132
轻奢々
轻奢々 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:27

    The best method I have found of creating a singleton is this:

    public class Singleton
    {
        static public Singleton Instance { get; } = new Singleton();
        private Singleton() { ... }
    }
    

    It is very concise, and more importantly, is also thread safe, which can be very troublesome to detect and fix as an application matures.


    Update: To show it is lazy...

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    
    namespace SingletonTest
    {
        class MySingleton
        {
            static public MySingleton Instance { get; } = new MySingleton();
    
            private MySingleton() { Console.WriteLine("Created MySingleton"); }
    
            public void DoSomething() { Console.WriteLine("DoSomething"); }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                Console.WriteLine("Starting Main");
    
                MySingleton.Instance.DoSomething();
            }
        }
    }
    

    Output:

    Starting Main
    Created MySingleton
    DoSomething
    

提交回复
热议问题