一个例子:
class E
{
public static E e;
//...
};
我们应该使用此功能或在何种情况下使用此功能?感谢。
答案 0 :(得分: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;
}
}
}
答案 1 :(得分:0)
static
变量不能保存对实例中声明的任何其他内容的引用,而是静态变量/方法属于类型而不是实例一种类型。
考虑一下:
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.
}
}
许多用法都很多,它可以填满书籍。正如有人提到的,Singleton模式使用它。