为什么实例成员在单例类中是静态的?

Pan*_*kaj 0 c# singleton

这是一个单身人士班

public sealed class Singleton
{
    static Singleton instance=null;
    static readonly object padlock = new object();

    Singleton()
    {
    }

    public static Singleton Instance
    {
        get
        {
            lock (padlock)
            {
                if (instance==null)
                {
                    instance = new Singleton();
                }
                return instance;
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是static Singleton instance=null; 为什么这是静态的?

vc *_* 74 7

'instance'字段包含唯一实例的引用.

它存储在静态变量中,因为它的范围必须是类本身而不是特定实例.


Ica*_*rus 5

因为您在静态属性(实例)中引用变量,所以无法在静态方法或属性中引用实例变量.

拥有Singleton的想法是只运行一个且只有一个实例.