gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:05:53 25 4
gpt4 key购买 nike

我正在查看一位同事编写的一些代码,而我预期的情况并非如此。这是代码:

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。我没想到的事情。如果 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 type 访问 .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;

关于c# - 试图了解静态在这种情况下是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11527067/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com