当前位置:网站首页>C# 单例模式

C# 单例模式

2022-08-10 01:18:00 ou.cs

using System;

namespace 单例模式
{
    
    internal class Program
    {
    
        public abstract class Singletion<T> where T : new()
        {
    

            private static T instance;
            private static readonly object obj = new object();
            public static T Instance
            {
    
                get
                {
    
                    if (instance == null)
                    {
    
                        lock (obj)
                        {
    
                            if (instance == null)
                                instance = new T();
                        }
                    }
                    return instance;
                }
            }

        }

        static void Main(string[] args)
        {
    
            //Test.Instance.val = 444;
            //Console.WriteLine(Test.Instance.val);
            Console.WriteLine(Singletion<Test>.Instance.val);

            //Console.WriteLine(Test.Instance.Equals(Singletion<Test>.Instance));
        }


        public class Test 
        {
    
            public int val = 123;
            public string str = "123";
        }
    }
}

    public abstract class Singletion<T> where T : new()
    {
    

        private static T? instance= default;

        private static readonly object obj = new object();
        public static T Instance
        {
    
            get
            {
    
                if (instance == null)
                {
    
                    lock (obj)
                    {
    
                        if (instance == null)
                            instance = new T();
                    }
                }
                return instance;
            }
        }
    }
原网站

版权声明
本文为[ou.cs]所创,转载请带上原文链接,感谢
https://blog.csdn.net/weixin_44291381/article/details/126174179