An obvious singleton implementation for .NET?

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

    I have just started to program in c# (coming from C++ its a breath of fresh air) and this is what I use to implement singleton patterns.

    public sealed class MyClass
    {    
        #region make singleton
    
        static readonly Lazy<MyClass> _singleton =
            new Lazy<MyClass>(() => new MyClass());
    
        public static MyClass Singleton
        {
            get { return _singleton.Value; }
        }
    
        private MyClass() { Initialize() };
    
        #endregion
    
        Initialize() { /*TODO*/ };
    }
    
    0 讨论(0)
提交回复
热议问题