相关疑难解决方法(0)

C#中一个好的线程安全单例通用模板模式是什么

我有以下C#单例模式,有什么方法可以改进它吗?

    public class Singleton<T> where T : class, new()
    {

        private static object _syncobj = new object();
        private static volatile T _instance = null;
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncobj)
                    {
                        if (_instance == null)
                        {
                            _instance = new T();
                        }
                    }
                }
                return _instance;
            }
        }

        public Singleton()
        { }

    }
Run Code Online (Sandbox Code Playgroud)

首选用法示例:

class Foo : Singleton<Foo> 
{
} 
Run Code Online (Sandbox Code Playgroud)

相关:

.NET的一个明显的单例实现?

c# design-patterns

31
推荐指数
4
解决办法
2万
查看次数

标签 统计

c# ×1

design-patterns ×1