public sealed class Singleton
{
Singleton() {}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
static Nested() {}
internal static readonly Singleton instance = new Singleton();
}
}
我希望在我当前的 C# 应用程序中实现 Jon Skeet's Singleton pattern。
我对代码有两个疑问
internal static readonly Singleton instance = new Singleton();
有什么叫闭包?
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
这个评论对我们有什么启示?
最佳答案
你真的需要这种模式吗?你确定你不能逃脱:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
public static Singleton Instance { get { return instance; } }
static Singleton() {}
private Singleton() {}
}
关于c# - Jon Skeet 的 Singleton 澄清,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2550925/