参考 http://www.yoda.arachsys.com/csharp/singleton.html

双lock的singleton性能非常差,这里推荐inner class的方式,并且加上泛型。

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

public static T Instance
{
get
{
return Nested.instance;
}
}

private class Nested
{
//suppress optimization in .net v1.1
static Nested() { }
internal static T instance = new T();
}
}
由于clr保证第一次调用静态类型都会初始化所有静态members,并且是线程安全的。不过这种方法的drawback就是T必须有public constructor,这往往违背了singleton的初衷,但事实上即使是private ctor,依然可以通过反射来实例化。

相关文章:

  • 2021-07-11
  • 2021-07-06
  • 2022-12-23
  • 2022-02-01
  • 2022-01-10
  • 2022-12-23
  • 2021-05-13
  • 2021-10-31
猜你喜欢
  • 2022-02-14
  • 2022-01-25
  • 2021-12-18
  • 2022-12-23
  • 2022-12-23
  • 2022-03-11
  • 2022-12-23
相关资源
相似解决方案