An obvious singleton implementation for .NET?

后端 未结 7 1142
轻奢々
轻奢々 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

    To prevent from having to copy the singleton code, you could make the type generic, as such:

    public abstract class Singleton
        where T: class, new()
    {
        public static T Instance
        {
            get { return Nested.instance; }
        }
    
        private class Nested
        {
            // Explicit static constructor to tell C# compiler
            // not to mark type as beforefieldinit
            static Nested() { }
    
            internal static readonly T instance = new T();
        }
    }
    
    public sealed class MyType : Singleton
    {
    }
    
    class Program
    {
        static void Main()
        {
            // two usage pattterns are possible:
            Console.WriteLine(
                ReferenceEquals(
                    Singleton.Instance, 
                    MyType.Instance
                )
            );
            Console.ReadLine();
        }
    }
    

提交回复
热议问题