析构函数是类的特殊成员函数,只要其类的对象超出范围,就会执行该析构函数。
它的名称与带有代字号(〜)的类的名称完全相同,例如,我们的类名为Demo。
public Demo() { // constructor Console.WriteLine("Object is being created"); } ~Demo() { //destructor Console.WriteLine("Object is being deleted"); }
让我们看一个示例,以学习如何在C#中使用Destructor。
using System; namespace LineApplication { class Line { private double length; // Length of a line public Line() { // constructor Console.WriteLine("Object is being created"); } ~Line() { //destructor Console.WriteLine("Object is being deleted"); } public void setLength( double len ) { length = len; } public double getLength() { return length; } static void Main(string[] args) { Line line = new Line(); //设置线长 line.setLength(6.0); Console.WriteLine("Length of line : {0}", line.getLength()); } } }
输出结果
Object is being created Length of line : 6 Object is being deleted