辛格尔顿由乔恩飞碟双向澄清双向、格尔、乔恩

2023-09-02 01:26:53 作者:染指旳沵唇

 公共密封类辛格尔顿
{
    辛格尔顿()
    {
    }

    公共静态单例
    {
        得到
        {
            返回Nested.instance;
        }
    }

    类嵌套
    {
        //显式静态构造函数来告诉C#编译器
        //没有标记类型beforefieldinit
        静态嵌套()
        {
        }

        内部静态只读Singleton实例=新辛格尔顿();
    }
}
 

我希望实现乔恩斯基特的Singleton模式的在我的C#当前应用程序。

我对code两个疑点

这怎么可能访问外部类嵌套类里面?我的意思是

 内部静态只读Singleton实例=新辛格尔顿();
 

时的一些所谓的封?

我没有得到这条评论

  //显式静态构造函数来告诉C#编译器
//没有标记类型beforefieldinit
 
伊劳伊 辛格尔顿 搜狗百科

这是什么意见建议我们呢?

解决方案

没有,这是没有任何关系闭包。嵌套类可以访问其外部类的私有成员,包括这里的私有的构造。

阅读beforefieldinit 我的文章。您可能会或可能不希望无操作静态构造 - 它取决于懒惰保证你所需要的。你应该知道,.NET 4 changes中的实际的类型初始化语义有点(仍然在规格,但比以前懒)。

你的真正的需要这种模式有关系吗?你确定你不能逃脱:

 公共密封类辛格尔顿
{
    私人静态只读Singleton实例=新辛格尔顿();
    公共静态单例{{返回实例; }}

    静态辛格尔顿(){}
    私人辛格尔顿(){}
}
 

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();
    }
}

I wish to implement Jon Skeet's Singleton pattern in my current application in C#.

I have two doubts on the code

How is it possible to access the outer class inside nested class? I mean

internal static readonly Singleton instance = new Singleton();

Is something called closure?

I did not get this comment

// 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.

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() {}
}