简体   繁体   中英

C# How to solve the problem that the destructor can't be displayed

code

        using System;
        namespace Destructor
      {
        class ClassA {
            public ClassA() {
                Console.WriteLine("ClassAConstructor");
            }
            ~ClassA() {
                Console.WriteLine("ClassADestructor");
            }

        }

        class ClassB
        {
            public ClassB()
            {
                Console.WriteLine("ClassBConstructor");
            }
            ~ClassB()
            {
                Console.WriteLine("ClassBDestructor");
            }
            public void CreateObject()
            {
                Console.WriteLine("intoClassB.CreateObject()");
                ClassA classA = new ClassA();
                Console.WriteLine("outClassB.CreateObject()");
            }
        }
        class Test
        {
            static void Main(string[] args)
            {
                {
                    Console.WriteLine("intoMain");
                    ClassB classB = new ClassB();
                    classB.CreateObject();
                    Console.WriteLine("outMain");
                }

                GC.Collect();
            }

        }
    }

result在此处输入图像描述

intoMain ClassBConstructor intoClassB.CreateObject() ClassAConstructor outClassB.CreateObject() outMain ClassADestructor

D:\Resources\c#-workspace\FristCosole\FristCosole\Destructor\bin\Debug\netcoreapp3.1\Destructor.exe (进程 12796)已退出,代码为 0。 按任意键关闭此窗口. . .

environment: visual studio 2019
Operation mode: ctrl+f5

Why only show the ClassA destructor and not the ClassB destructor? How do I see the ClassB destructor in the console?

The lifetime of a local variable is the lifetime of the activation of control within the local variable scope that declares it. So your local is alive until the end of main. That alone is sufficient to explain why it is not collected, but there are subtleties here that we should explore in more depth.

I suppose you are using debug mode, so your local is still rooted (with allows you to inspects program after its end). Switching to release mode will propably solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM