且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在具有性能约束的 C# 中实现单例设计模式的***方法是什么?

更新时间:2022-03-05 01:46:00

转述自 C# in Depth:在 C# 中有多种不同的实现单例模式的方法,从对于完全延迟加载、线程安全、简单且高性能的版本而言,不是线程安全的.

Paraphrased from C# in Depth: There are various different ways of implementing the singleton pattern in C#, from Not thread-safe to a fully lazily-loaded, thread-safe, simple and highly performant version.

***版本 - 使用 .NET 4 的 Lazy 类型:

Best version - using .NET 4's Lazy type:

public sealed class Singleton
{
  private static readonly Lazy<Singleton> lazy =
      new Lazy<Singleton>(() => new Singleton());

  public static Singleton Instance { get { return lazy.Value; } }

  private Singleton()
  {
  }
}

它很简单而且性能很好.它还允许您使用 IsValueCreated 属性,如果你需要的话.

It's simple and performs well. It also allows you to check whether or not the instance has been created yet with the IsValueCreated property, if you need that.