GC.GetGeneration() returns always 0 for int variable even after calling GC.Collect() in C#

nov*_*ato 1 .net c# garbage-collection

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));
Run Code Online (Sandbox Code Playgroud)

The output should be

0
1
Run Code Online (Sandbox Code Playgroud)

as int j is surviving garbage collection But I am getting

0
0
Run Code Online (Sandbox Code Playgroud)

我不明白为什么会发生这种情况,因为int它也是 C# 中的一个对象。PS:我试过在调试和发布模式下运行项目。

Jon*_*asH 5

正如评论中提到的。anint是一种值类型,不会被垃圾收集器跟踪。由于GetGeneration需要 an object, int 将被装箱。即将创建一个新对象。该新对象将始终在第 0 代中分配。下次调用时GetGeneration将发生相同的事情。

所以你的结果符合预期。