【问题标题】:What's the functionality of a class has a static member of it self? [closed]一个类的功能是什么,它本身有一个静态成员? [关闭]
【发布时间】:2016-06-07 09:46:51
【问题描述】:

一个例子:

class E
{
    public static E e;
    //...
};

它的功能是什么,或者我们应该在什么情况下使用它?谢谢。

【问题讨论】:

  • 它可以是任何东西。请提供MCVE
  • 可能用于单例。
  • 或者某种原型对象。
  • 由于末尾有分号,我认为这是 C++ 问题。
  • C++ 和 C# 的答案可能不同。你在找哪一个?

标签: c# c++ static-members


【解决方案1】:

其中一种用法可以是实现单例(当您需要一个只有一个实例的类,并且您需要提供对该实例的全局访问点):Implementing Signleton

public class Singleton
{
  private static Singleton instance;

  private Singleton() {}

 public static Singleton Instance
   {
      get 
      {
         if (instance == null)
         {
            instance = new Singleton();
         }
         return instance;
      }
   }
}

【讨论】:

【解决方案2】:

static 变量不能包含对实例中声明的任何其他内容的引用,而是静态变量/方法属于 type 而不是 类型的实例

考虑一下:

public class TestClass
{
    private static string _testStaticString;
    private string _testInstanceString;

    public void TestClass()
    {
        _testStaticString = "Test"; //Works just fine
        _testInstanceString = "Test";

        TestStatic();
    }

    private static void TestStatic()
    {
        _testInstanceString = "This will not work"; //Will not work because the method is static and belonging to the type it cannot reference a string belonging to an instance.
        _testStaticString = "This will work"; //Will work because both the method and the string are static and belong to the type.
    }
}

用法多到可以写满书。正如有人提到的,单例模式利用了它。

【讨论】:

    猜你喜欢
    • 2023-03-23
    • 2021-10-05
    • 2012-01-21
    • 2010-09-27
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2015-06-19
    • 2012-06-08
    相关资源
    最近更新 更多