考虑以下代码:
public class Class1
{
public static int c;
~Class1()
{
c++;
}
}
public class Class2
{
public static void Main()
{
{
var c1=new Class1();
//c1=null; // If this line is not commented out, at the Console.WriteLine call, it prints 1.
}
GC.Collect();
GC.WaitForPendingFinalizers();
Console.WriteLine(Class1.c); // prints 0
Console.Read();
}
}
Run Code Online (Sandbox Code Playgroud)
现在,即使main方法中的变量c1超出范围并且在GC.Collect()调用时没有被任何其他对象进一步引用,为什么它没有在那里完成?
我正在学习来自python的 C#,并希望知道C#垃圾收集器是如何工作的 - 我发现一旦我弄清楚它在幕后做了什么,我就更了解python,并希望避免制作那种菜鸟我在学习python时最初犯的错误.
我一直无法找到任何关于何时收集垃圾的物品的明确解释,并留下诸如此类的问题
对这些问题的回答,甚至更好地清楚地概述实际发生的事情将赢得cookie(或upvotes),如果你的答案与python的做事方式相比更好.我对哪个更好,只是细节不感兴趣.我在programmers.stackexchange上的原始帖子上的答案将非常感谢...