Jon Skeet 的 Singleton 澄清 [英] Singleton by Jon Skeet clarification
问题描述
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 的单例模式.
I wish to implement Jon Skeet's Singleton pattern in my current application in C#.
我对代码有两个疑问
如何访问嵌套类内部的外部类?我是说
How is it possible to access the outer class inside nested class? I mean
internal static readonly Singleton instance = new Singleton();
什么叫做闭包?
我无法理解此评论
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit
这条评论对我们有什么启示?
what does this comment suggest us?
推荐答案
不,这与闭包无关.嵌套类可以访问其外部类的私有成员,包括此处的私有构造函数.
No, this is nothing to do with closures. A nested class has access to its outer class's private members, including the private constructor here.
阅读我关于 beforefieldinit 的文章.您可能需要也可能不需要 no-op 静态构造函数 - 这取决于您需要什么惰性保证.您应该知道 .NET 4 稍微改变了实际类型初始化语义(仍在规范范围内,但比以前更懒惰).
Read my article on beforefieldinit. You may or may not want the no-op static constructor - it depends on what laziness guarantees you need. You should be aware that .NET 4 changes the actual type initialization semantics somewhat (still within the spec, but lazier than before).
你真的需要这种模式吗?你确定你不能逃脱:
Do you really need this pattern though? Are you sure you can't get away with:
public sealed class Singleton
{
private static readonly Singleton instance = new Singleton();
public static Singleton Instance { get { return instance; } }
static Singleton() {}
private Singleton() {}
}
这篇关于Jon Skeet 的 Singleton 澄清的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!