C# · 12月 29, 2021

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 instanceSingletonInstance temp2 = temp.Instance;