自动属性初始化程序Singleton实现 [英] Auto-property initializer Singleton implementation

查看:107
本文介绍了自动属性初始化程序Singleton实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,使用全新的C#6,我们得到了那些简洁的自动属性初始化程序.我以为我最好还是利用这些优势来制作比以往更简洁的单例.显然,其他人也有这个想法.

So, with the brand new C# 6 we got those neat auto-property initializers. I thought I might as well take advantage of these to make more concise singletons than ever. Apparently someone else got that idea, too.

public sealed class Singleton
{
    public static Singleton Instance { get; } = new Singleton();
    private Singleton() { /* some initialization code */ }
}

我的问题是:

  1. 线程安全性如何?
  2. 它有多懒,或者实际创建实例的时间是什么? (不是优先事项,但对以后的参考很有用)
  3. 总体来说这是个好主意吗?

(它看起来可能类似于此问题,但不是)

(it might look similar to this question, but it's not)

推荐答案

您的代码将扩展为以下内容:

Your code will be expanded to the following:

public sealed class Singleton
{
    private static readonly Singleton <Instance>k__BackingField = new Singleton();
    public static Singleton Instance { get { return <Instance>k__BackingField; } }
    private Singleton() { /* some initialization code */ }
}

(<Instance>k__BackingField是编译器生成的字段的无法说出的名字.)

(<Instance>k__BackingField is the unspeakable name of the compiler-generated field.)

因此,您代码的属性将与上面的代码完全相同.也就是说,这种模式是线程安全的,根据情况可能是个好主意.

So, the properties of your code will be exactly the same as of the code above. Namely, this pattern is thread-safe and it can be a good idea, depending on circumstances.

假设您在访问Instance之前没有访问任何其他这种类型的静态成员,那么延迟的确切程度取决于运行时.通常,它类似于实例是在第一次使用Jem编译的可以访问Instance的方法时创建的",但是您对此没有任何保证.

Assuming you're not accessing any other static members of this type before accessing Instance, then the exact degree of laziness is up to the runtime. Commonly, it will be something like "the instance is created the first time a method that could access Instance is JIT-compiled", but you don't have any guarantee about this.

如果要确保实例是在第一次访问Instance之前创建的,请向您的类添加一个空的静态构造函数. (这可能会对性能产生较小的负面影响,但对您而言可能并不重要.)

If you want to make sure that the instance is created just before Instance is accessed for the first time, add an empty static constructor to your class. (This can have a small negative effect on performance, but that probably won't matter to you.)

由于大多数内容并不是真正针对C#6的,因此进一步的信息很好的来源是Jon Skeet关于单个静态构造函数/类型初始化器.

Since most of this is not really specific to C# 6, a good source of further information would be Jon Skeet's articles about singletons and static constructors/type initializers.

这篇关于自动属性初始化程序Singleton实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆