析构函数是通过下面的形式声明的: attributes(可选) 一个类只能有一个析构函数。 无法继承或重载析构函数。 无法调用析构函数。它们是被自动调用的。 析构函数既没有修饰符,也没有参数。例如,下面是类 MyClass 的析构函数的声明: ~ MyClass() { // Cleanup statements.} protected override void Finalize(){ try { // Cleanup statements. } finally { base.Finalize(); }} 程序员无法控制何时调用析构函数,因为这由垃圾回收器决定的。垃圾回收器检查是否存在应用程序不再使用的对象。它认为这些对象符合销毁条件并回收这些对象占用的内存。程序退出时也会调用析构函数。 可以通过调用 GC.Collect 方法强制进行垃圾回收,但大多数情况下应避免这样做,因为这样会导致出现性能问题。有关更多信息,请参见强制垃圾回收。 示例 // Destructors1.csusing System;class First{ ~First() { Console.WriteLine("First’s destructor is called"); }}class Second: First{ ~Second() { Console.WriteLine("Second’s destructor is called"); }}class Third: Second{ ~Third() { Console.WriteLine("Third’s destructor is called"); }}public class MainClass { public static void Main() { Third myObject = new Third(); }} 资源的显式释放 |