什么是 C# 中好的线程安全单例通用模板模式 [英] What's a good threadsafe singleton generic template pattern in C#

查看:21
本文介绍了什么是 C# 中好的线程安全单例通用模板模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have the following C# singleton pattern, is there any way of improving it?

    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()
        { }

    }

首选用法示例:

class Foo : Singleton<Foo> 
{
} 

相关:

明显的 .NET 单例实现?

推荐答案

根据 Jon Skeet 在 实施单例模式在 C# 中,您发布的代码实际上被认为是坏代码,因为根据 ECMA CLI 标准检查时,它看起来已损坏.

According to Jon Skeet in Implementing the Singleton Pattern in C# the code you posted is actually considered as bad code, because it appears broken when checked against the ECMA CLI standard.

还要注意:每次使用新类型的 T 实例化对象时,它都会变成另一个实例;它不会反映在您原来的单身人士中.

Also watch out: everytime you instantiate your object with a new type of T, it becomes another instance; it doesn't get reflected in your original singleton.

这篇关于什么是 C# 中好的线程安全单例通用模板模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆