gpt4 book ai didi

c# - 单例缩短实现

转载 作者:太空狗 更新时间:2023-10-29 22:58:29 24 4
gpt4 key购买 nike

我总是看到单例是这样实现的:

public class Singleton
{
static Singleton instance;
static object obj = new object();

public static Singleton Instance
{
get
{
lock (obj)
{
if (instance == null)
{
instance = new Singleton();
}
return instance;
}
}
}

protected Singleton() { }
}

这样实现有什么问题吗:

public class Singleton
{
static readonly Singleton instance = new Singleton();
public static Singleton Instance
{
get { return instance; }
}

protected Singleton() { }
}

?它在与第一个实现相同的时刻进行延迟初始化,所以我想知道为什么这不是一个流行的解决方案?它也应该更快,因为不需要条件、锁定并且该字段被标记为只读,这将让编译器进行一些优化

请不要谈论单例(反)模式本身

最佳答案

CLR will initialize the field upon the first use该(或任何其他静态)字段的。它promises to do so in a thread-safe manner .

您的代码之间的区别在于,第一段代码支持线程安全的惰性初始化,而第二段代码则不支持。这意味着当您的代码从不访问 Singleton.Instance 时第一个代码,没有 new Singleton()将永远被创造。对于第二堂课,它会在您访问 Instance 时立即执行。 或(直接或间接)该类的任何其他静态成员。更糟糕的是 - 它 may be initialized before that因为你缺少静态构造函数。

喜欢更短和更易读的代码,因为 .NET 4 你可以使用 Lazy<T>显着缩短第一个代码块:

public class Singleton
{
static readonly Lazy<Singleton> instance =
new Lazy<Singleton>(() => new Singleton());

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

static Singleton() { }
private Singleton() { }
}

作为Lazy<T>还有promises thread-safety .这将确保 new Singleton()只被调用一次,并且只在 Singleton.Instance 时被调用实际使用。

关于c# - 单例缩短实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27961062/

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