只有当对象所在代被 Collect 了,改对象所在代才会加 1 ,代值最大为 2
示例1:
1 using System; 2 3 namespace myMethod 4 { 5 class People{} 6 7 class lgs 8 { 9 static void Main() 10 { 11 People p = new People(); 12 Console.WriteLine(GC.GetGeneration(p)); // 0 13 14 GC.Collect(); 15 GC.Collect(); 16 17 Console.WriteLine(GC.GetGeneration(p)); // 2 18 19 Console.ReadKey(); 20 } 21 } 22 }
示例2:
1 using System; 2 3 namespace myMethod 4 { 5 class People{} 6 7 class lgs 8 { 9 static void Main() 10 { 11 People p = new People(); 12 Console.WriteLine(GC.GetGeneration(p)); // 0 13 14 GC.Collect(); //递增为 1 15 GC.Collect(0); //只Collect 0 代,1代未Collect,所以仍然为 1 16 17 Console.WriteLine(GC.GetGeneration(p)); // 1 18 19 Console.ReadKey(); 20 } 21 } 22 }
示例3:
1 using System; 2 3 namespace myMethod 4 { 5 class People{} 6 7 class lgs 8 { 9 static void Main() 10 { 11 People p = new People(); 12 Console.WriteLine(GC.GetGeneration(p)); // 0 13 14 GC.Collect(); //递增为 1 15 GC.Collect(2); //Collect 0、1、2 代,1代被Collect,所以递增1,变为 2 16 17 Console.WriteLine(GC.GetGeneration(p)); // 2 18 19 Console.ReadKey(); 20 } 21 } 22 }
参考:https://www.jb51.net/article/41819.htm