C# in Depth 中建议的单例模式实现是
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
ReSharper 建议使用自动属性和 C# 6 自动属性初始化程序来简化此操作:
public sealed class Singleton
{
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance { get; } = new Singleton();
}
这看起来确实更简单。使用这种简化有不利的一面吗?
最佳答案
现场https://sharplab.io您可以查看 IL 代码,在这两种情况下,IL 代码都是相似的。所以这应该以同样的方式工作。
关于c# - 单例模式 - 一个简化的实现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45728957/