什么是C#中的良好线程单通用模板模式 [英] What's a good threadsafe singleton generic template pattern in C#
本文介绍了什么是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()
{ }
}
preferred使用例子:
Preferred usage example:
class Foo : Singleton<Foo>
{
}
相关
推荐答案
据乔恩斯基特在实施Singleton模式在C#中的code你贴实际上被认为是坏code,因为当对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屋!
查看全文