【发布时间】:2012-03-16 03:16:15
【问题描述】:
我正在经历here 中提到的以下单例实现。我了解静态构造函数在第一个静态方法调用之前或在实例化对象之前执行,但不了解它在这里的用途(甚至来自 cmets)。谁能帮我理解一下?
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Singleton()
{
}
private Singleton()
{
}
public static Singleton Instance
{
get
{
return instance;
}
}
}
【问题讨论】:
-
它在它下面的项目符号中进行了解释,特别是:
The laziness of type initializers is only guaranteed by .NET when the type isn't marked with a special flag called 'beforefieldinit'. Unfortunately, the C# compiler (as provided in the .NET 1.1 runtime, at least) marks all types which don't have a static constructor (i.e. a block which looks like a constructor but is marked static) as 'beforefieldinit'.所以,他希望尽可能晚地(懒惰地)构造new Singleton(),这是获得 C# 编译器的唯一方法这样做是提供一个空的静态构造函数。 -
原谅我的无知。什么是“类型初始化程序的惰性”。是在第一次请求时初始化吗?
-
没错。只有在这种情况下才能保证,否则运行时可以随时运行类型初始化程序,例如在加载类型后立即运行。有关详细说明,请参阅 Jay 答案中的链接。