【发布时间】:2011-03-30 19:10:35
【问题描述】:
请看下面的代码。我希望它打印 10 个,因为我已经明确调用了垃圾收集器。但我总是得到 0 或 20 作为输出。这是为什么呢?
void Main()
{
Panda[] forest_panda = new Panda[10];
for(int i=0; i<forest_panda.GetLength(0);i++)
{
forest_panda[i]=new Panda("P1");
}
for(int i=0; i<forest_panda.GetLength(0);i++)
{
forest_panda[i]=new Panda("P1");
}
System.GC.Collect();
Console.WriteLine("Total Pandas created is {0}",Panda.population);
}
class Panda
{
public static int population=0;
public string name;
public Panda(string name)
{
this.name = name;
population = population + 1;
}
~Panda()
{
population = population - 1;
}
}
请注意,Main 类是由 LINQPad(随“C# 4.0 in a Nutshell”一书附带的编辑器)自动创建的。我是 C# 新手。
【问题讨论】:
-
blogs.msdn.com/b/oldnewthing/archive/2010/08/09/10047586.aspx Raymond 博客首页上还有更多好文章。
-
为什么当你创建 20 个 Pandas 时它会打印 10 个?
-
@Rune FS 我没想到第二组 10 个 Pandas 会被 GCed。但现在我明白了它也可以被 GC,因为当我调用 GC 时,程序中不再引用它。
标签: c# garbage-collection destructor