试着理解静态在这种情况下是如何工作的

Jus*_*tin 6 .net c# oop

我正在看一些同事写的代码和我预期会发生的代码.这是代码:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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

private SingletonClass sc = SingletonClass.Instance.Instance.Instance.Instance.Instance.Instance;
Run Code Online (Sandbox Code Playgroud)

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

Ree*_*sey 12

如果Instance属性返回一个SingletonClass类,为什么我不能在返回的类上调用Instance属性,依此类推?

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

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

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

// This fails, because you're accessing it via an instance
// inst.Instance
Run Code Online (Sandbox Code Playgroud)

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

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; 
Run Code Online (Sandbox Code Playgroud)