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

前端之家收集整理的这篇文章主要介绍了c# – 试图了解静态在这种情况下是如何工作的前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在看一些同事写的代码和我预期会发生的代码.这是代码
  1. public class SingletonClass
  2. {
  3. private static readonly SingletonClass _instance = new SingletonClass();
  4.  
  5. public static SingletonClass Instance
  6. {
  7. get { return _instance; }
  8. }
  9.  
  10. private SingletonClass()
  11. {
  12. //non static properties are set here
  13. this.connectionString = "bla"
  14. this.created = System.DateTime.Now;
  15. }
  16. }

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

  1. 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是静态的,您必须通过以下类型访问它:

  1. SingletonInstance inst = SingletonInstance.Instance; // Access via type
  2.  
  3. // This fails,because you're accessing it via an instance
  4. // inst.Instance

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

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

猜你在找的C#相关文章