c# – 试图了解静态在这种情况下是如何工作的

我正在看一些同事写的代码和我预期会发生的代码.这是代码
public class SingletonClass
{
    private static readonly SingletonClass _instance = new SingletonClass();

    public static SingletonClass Instance
    {
        get { return _instance; }
    } 

    private SingletonClass()
    {
        //non static properties are set here
        this.connectionString = "bla"
        this.created = System.DateTime.Now;
    }
}

在另一堂课中,我希望能够做到:

private SingletonClass sc = SingletonClass.Instance.Instance.Instance.Instance.Instance.Instance;

它引用该类的相同实例.发生的事情是我只能有一个.实例.我没想到的东西.如果Instance属性返回一个SingletonClass类,为什么我不能在返回的类上调用Instance属性,依此类推?

解决方法

If the Instance property returns a SingletonClass class,why can’t I call the Instance property on that returned class and so on and so on?

因为您只能通过SingletonClass类型访问.Instance,而不能通过该类型的实例访问.Instance.

由于Instance是静态的,您必须通过以下类型访问它:

SingletonInstance inst = SingletonInstance.Instance; // Access via type

// This fails,because you're accessing it via an instance
// inst.Instance

当你试图链接这些时,你实际上是这样做的:

SingletonInstance temp = SingletonInstance.Instance; // Access via type

// ***** BAD CODE BELOW ****
// This fails at compile time,since you're trying to access via an instance
SingletonInstance temp2 = temp.Instance;

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...