c# - 单例模式 - 一个简化的实现?

标签 c# singleton resharper

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/

相关文章:

c# - ASP.NET SQL 问题和代码帮助

php - 实现 PHP 单例 : static class properties or static method variables?

ios - 使用单例创建基本样式助手类

ios - 如何实现在 Swift 中获取初始化数据的 Singleton?

.net - 当我检查空值时禁用空引用警告

c# - DotNetOpenAuth OpenID 提供商 "Sequence contains more than one element"

c# - Visual Studio 中具有智能感知的 Simple.Data Micro ORM(动态)

c# - 如何在 c#.net 桌面应用程序的标签上显示 "Lambda"或 "Mu"等符号

c# - Format Line 实际上没有格式化。

visual-studio - 通过 VS Test Explorer 运行时单元测试失败,但通过 Resharper 通过