An obvious singleton implementation for .NET?

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

    I always use this regular (non-lazy) one (you could nest it like the other examples): (requires using System.Reflection;)

    public class SingletonBase where T : class
    {
        static SingletonBase()
        {
        }
    
        public static readonly T Instance = 
            typeof(T).InvokeMember(typeof(T).Name, 
                                    BindingFlags.CreateInstance | 
                                    BindingFlags.Instance |
                                    BindingFlags.Public |
                                    BindingFlags.NonPublic, 
                                    null, null, null) as T;
    }
    

提交回复
热议问题