gpt4 book ai didi

c# - 哪个单例工具更好 C#

转载 作者:太空宇宙 更新时间:2023-11-03 13:46:46 25 4
gpt4 key购买 nike

<分区>

在 C# 中实现单例模式有多种不同的方法。我将以优雅的相反顺序在这里展示它们,从最常见的非线程安全的版本开始,一直到完全延迟加载、线程安全、简单且高性能的版本。

我在谷歌上查找“如何实现单例”并找到了 3 种方式,哪种单例实现更好 C#?

1) 此代码使用 lock()

public class Singleton

{
// Static object of the Singleton class.
private static volatile Singleton _instance = null;

/// <summary>
/// The static method to provide global access to the singleton object.
/// </summary>
/// <returns>Singleton object of class Singleton.</returns>
public static Singleton Instance()
{
if (_instance == null)
{
lock (typeof(Singleton))
{
_instance = new Singleton();
}
}
return _instance;
}

/// <summary>
/// The constructor is defined private in nature to restrict access.
/// </summary>
private Singleton() { }

}

2) 这段代码是静态初始化

/// <summary>
/// A sealed class providing access to it's ONLY readonly static instance.
/// </summary>
sealed class SingletonCounter
{
public static readonly SingletonCounter Instance =
new SingletonCounter();

private SingletonCounter() {}
}

3) 此代码使用 Lazy 类型。

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com