我的一个类在应用程序执行期间收集统计信息,我希望在应用程序完成时将此统计信息存储到磁盘.我从来没有在我的程序中销毁这个类,所以我试图将日志存储到文件中:
~Strategy()
{
foreach(var item in statisticItems)
{
log.WriteLine(item.Text); // log is AutoFlush
}
}
Run Code Online (Sandbox Code Playgroud)
但是我没有看到我期望看到的日志,并且在析构函数调用时我也无法在调试器中"捕获".
问题:
请参阅下面的代码.我希望它打印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;
}
}
Run Code Online (Sandbox Code Playgroud)
请注意,Main的类是由LINQPad("Nutshell中的C#4.0"一书中的编辑器)自动创建的.我是C#的新手.