https://bbs.csdn.net/topics/330120571/
c# 环形引用 垃圾回收机制是会清理掉的。
static int a = 0;public class ClassA{public ClassB classB;public ClassA(){classB = new ClassB(this);a++;}~ClassA(){Console.WriteLine("ClassA");}}public class ClassB{ClassA classA1;public ClassB(ClassA classA){classA1 = classA;}~ClassB(){Console.WriteLine(a + "");Console.WriteLine("ClassB");}}
测试函数:
List<ClassA> lis &#61; new List<ClassA>();{lis.Add(new ClassA());lis.Add(new ClassA());lis.Add(new ClassA());lis.Add(new ClassA());lis.Add(new ClassA());lis.Add(new ClassA());lis.Add(new ClassA());lis.Add(new ClassA());lis.Clear();GC.Collect();Thread.Sleep(10);}}
输出&#xff1a;
8
ClassB
ClassA
8
ClassB
ClassA
8
ClassB
ClassA
8
ClassB
ClassA
8
ClassB
ClassA
8
ClassB
ClassA
8
ClassB
ClassA
8
ClassB
ClassA