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();
}
}
Run Code Online (Sandbox Code Playgroud)
我希望在我目前的C#应用程序中实现Jon Skeet的Singleton模式.
我对代码有两个疑问
如何访问嵌套类中的外部类?我的意思是
internal static readonly Singleton instance = new Singleton();
Run Code Online (Sandbox Code Playgroud)
有什么叫封闭吗?
我无法理解这个评论
// Explicit static constructor to tell C# compiler
// not to mark type as beforefieldinit …Run Code Online (Sandbox Code Playgroud)public class MySingletonClass
{
public MySingletonClass()
{
_mySingletonObj = Instance();
}
public static MySingletonClass Instance()
{
if (_mySingletonObj == null)
{
lock (typeof(lockObject))
{
if (_mySingletonObj == null)
_mySingletonObj = new MySingletonClass();
}
}
return _mySingletonObj ;
}
}
MySingletonClass _myObj = new MySingletonClass();
Run Code Online (Sandbox Code Playgroud)
这个作为公共建设者的单身人士......?
谢谢