2016-06-07 44 views
-2

一个例子:类有什么功能有自己的静态成员?

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

什么的这样或在其下的功能情况下,我们应该用这个?谢谢。

+3

它可以是任何东西。请提供[MCVE](http://stackoverflow.com/help/mcve) – dotctor

+1

可能用于单身人士。 – Jarod42

+0

或者可能是某种原型对象。 – TartanLlama

回答

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模式使用它。

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; 
     } 
    } 
} 
+0

单身人士在C#中的最终链接:http://csharpindepth.com/Articles/General/Singleton.aspx – Henrik

相关问题