csharp C#.cs中的析构函数

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp C#.cs中的析构函数相关的知识,希望对你有一定的参考价值。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Destructor
{
    class First
    {
        ~First()
        {
            System.Diagnostics.Trace.WriteLine(@"'First' Destructor is called");
        }
    }

    class Second:First
    {
        ~Second()
        {
            System.Diagnostics.Trace.WriteLine(@"'Second' Destructor is called");
        }
    }

    class Third:Second
    {
        ~Third()
        {
            System.Diagnostics.Trace.WriteLine(@"'Third' Destructor is called");
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            //SEE TRACE LOGS FROM 'OUTPUT' WINDOW AFTER CLOSING THE PROGRAM
            //Destructor are called and followed in order of Inheritance Chain MostDerived to LeastDerived (that means Third>Second>First)
            new Third(); //Here we are creating an instance of the most derived class (Third) 

            Console.WriteLine("Press any key");
            Console.Read();
        }
    }
}


/* Output (to VS Output Window):
    Third's destructor is called.
    Second's destructor is called.
    First's destructor is called.
*/

以上是关于csharp C#.cs中的析构函数的主要内容,如果未能解决你的问题,请参考以下文章

在 C++11 中的析构函数之后覆盖标识符

C++中基类的析构函数为什么要用virtual虚析构函数

C# 使用 AWS lambda 时,我可以确定函数中的析构函数会被执行吗?

从 C++ 中的析构函数中恢复对象?

在 C# 中,类中的析构函数和 Finalize 方法有啥区别?

C++中的析构函数