GC.GetGeneration()returnsalways0forintvariableevenaftercallingGC.Collect()inC#
c#
Below is code snippet in which I am getting generation of variable int j before and after calling garbage collector.
int j = 30;
WriteLine(GC.GetGeneration(j) );
GC.Collect();
WriteLine(GC.GetGeneration(j));
The output should be
0
1
as int j is surviving garbage collection But I am getting
0
0
我不明白为什么会发生这种情况,因为int它也是 C# 中的一个对象。PS:我试过在调试和发布模式下运行项目。
回答
正如评论中提到的。anint是一种值类型,不会被垃圾收集器跟踪。由于GetGeneration需要 an object, int 将被装箱。即将创建一个新对象。该新对象将始终在第 0 代中分配。下次调用时GetGeneration将发生相同的事情。
所以你的结果符合预期。
THE END
二维码