2012-09-03 70 views
3

希望你不介意,我可能會錯過一些東西;我只是需要一些澄清以下情況:如果一個對象一個包含靜態列表,並在靜態列表中的條目的參考和對象一個超出範圍,會是垃圾集?我是否需要設置對象a的對靜態列表的引用以及對該列表中的條目的引用在它變爲符合條件之前爲null?對象引用靜態成員垃圾處理

我的理解是靜態列表包含將現場爲應用程序的生命週期對象,因此,因爲對象我想一個仍引用在靜態列表中的條目,但它仍然是主要依賴對象仍然活着的物體的圖形?

在此先感謝

回答

2

首先,對象不會超出範圍,變量就是這樣。大多數情況下,區別在於語義,但在這裏至關重要。

讓我們創建的,你談什麼具體的例子:

private static List<string> static_strings = new List<string>();//this won't be 
                   //collected unless we 
                   //assign null or another 
                   //List<string> to static_strings 
public void AddOne() 
{ 
    string a = new Random().Next(0, 2000).ToString();//a is in scope, it refers 
                //to a string that won't be collected. 
    static_strings.Add(a);//now both a and the list are ways to reach that string. 
    SomeListHolder b = new SomeListHolder(static_strings);//can be collected 
                 //right now. Nobody cares 
                 //about what an object refers 
                 //to, only what refers to it. 
}//a is out of scope. 
public void RemoveOne() 
{ 
    if(static_strings.Count == 0) return; 
    a = static_strings[0];//a is in scope. 
    static_strings.RemoveAt(0);//a is the only way to reach that string. 
    GC.Collect();//Do not try this at home. 
    //a is in scope here, which means that we can write some code here 
    //that uses a. However, garbage collection does not depend upon what we 
    //could write, it depends upon what we did write. Because a is no 
    //longer used, it is highly possible that it was collected because 
    //the compiled code isn't going to waste its time holding onto referenes 
    //it isn't using. 
} 

如這裏看到的,範圍是什麼,可達性就是一切。

在引用靜態的對象的情況下,它引用的內容是無關緊要的,只是引用了它。

特別是,請注意,這意味着循環引用不會阻止收集項目,這與某些引用計數垃圾收集方法不同。

+0

謝謝 - 我明白了 - 我錯過了你提出的關於它不關心對象是指什麼的問題,而是從根對象開始引用它。由於我的靜態列表不是指「a」,因此只要「a」不在範圍內,我們都很樂意參與GC。 – Zivka

4

在你的情況靜態列表會生活,但一個將被垃圾收集監守你無法從其他任何地方訪問它,並沒有任何意義,以保持它在內存中。您不需要將參考空值歸入靜態列表。