【问题标题】: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;
//...
};
它的功能是什么,或者我们应该在什么情况下使用它?谢谢。
【问题讨论】:
标签:
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.
}
}
用法多到可以写满书。正如有人提到的,单例模式利用了它。