只是做了一些練習,並突破這個例子。我發現早期創建的列表成員的引用仍然存在,爲什麼?爲什麼對象仍然活着?
anotherShoe
和newShoe
仍然具有分配給其參考成員的值,但正如您所看到的那樣,實際的對象已被清除。我知道我可以爲它們分配空值,但是當它們的參考對象已經被List<T>.Clear()
時,它們不會被自動清空/垃圾收集?
謝謝。
List<Shoe> shoeCloset = new List<Shoe>();
shoeCloset.Add(new Shoe() { styles = Styles.Sneakers, colour = "Red" });
shoeCloset.Add(new Shoe() { styles = Styles.Sandals, colour = "Green" });
shoeCloset.Add(new Shoe() { styles = Styles.Flipflops, colour = "Yellow"});
shoeCloset.Add(new Shoe() { styles = Styles.Loafers, colour = "Brown" });
shoeCloset.Add(new Shoe() { styles = Styles.Wingtips, colour = "Blue" });
//int numberOfShoes = shoeCloset.Count;
//foreach (Shoe shoe in shoeCloset)
//{
// shoe.styles = Styles.Sneakers;
// shoe.colour = "White";
//}
shoeCloset.RemoveAt(3);
Shoe newShoe = shoeCloset[2];
Shoe anotherShoe = shoeCloset[1];
anotherShoe.colour = "Grey";
anotherShoe.colour = "Green";
if (shoeCloset.Contains(anotherShoe))
{
Console.WriteLine("Contains another shoe");
}
shoeCloset.Clear();
anotherShoe.ToString(); //<---this still contains values after shoeCloset has been cleared.
newShoe.ToString(); //<---this still contains values after shoeCloset has been cleared.
'Clear()'不處理對象,它只切割列表和實例化對象之間的引用。這個是正常的。您仍然有一些參考指向前兩個對象,因此它們不會被GC處置。 – Vlad 2014-10-08 20:24:13
你的前提是錯誤的。 List.Clear()只是清除列表 - 從列表中刪除對象。但只要引用對象存在垃圾收集器不能釋放它佔用的內存。 – 2014-10-08 20:24:16
你在哪裏清除「anotherShoe」的內容,這兩行的目的是什麼'notherShoe.colour =「Gray」; anotherShoe.colour =「綠色」;'你有沒有使用調試器...?你是否熟悉「Null」這個詞在轉讓方面的問題 – MethodMan 2014-10-08 20:24:42