C# ---- GC中代的递增规律

时间:2022-10-13 06:47:20

只有当对象所在代被 Collect 了,改对象所在代才会加 1 ,代值最大为 2

示例1:

 using System;

 namespace myMethod
{
class People{} class lgs
{
static void Main()
{
People p = new People();
Console.WriteLine(GC.GetGeneration(p)); // GC.Collect();
GC.Collect(); Console.WriteLine(GC.GetGeneration(p)); // Console.ReadKey();
}
}
}

示例2:

 using System;

 namespace myMethod
{
class People{} class lgs
{
static void Main()
{
People p = new People();
Console.WriteLine(GC.GetGeneration(p)); // GC.Collect(); //递增为 1
GC.Collect(); //只Collect 0 代,1代未Collect,所以仍然为 1 Console.WriteLine(GC.GetGeneration(p)); // Console.ReadKey();
}
}
}

示例3:

 using System;

 namespace myMethod
{
class People{} class lgs
{
static void Main()
{
People p = new People();
Console.WriteLine(GC.GetGeneration(p)); // GC.Collect(); //递增为 1
GC.Collect(); //Collect 0、1、2 代,1代被Collect,所以递增1,变为 2 Console.WriteLine(GC.GetGeneration(p)); // Console.ReadKey();
}
}
}

参考:https://www.jb51.net/article/41819.htm