C# 程序中的析构函数是什么?
析构函数是类的特殊成员函数,每当类的对象超出作用域时该函数就会被执行。
它与类名完全相同,只是前面加上了波浪号 (~),例如我们的类名为 Demo。
public Demo() { // constructor Console.WriteLine("Object is being created"); } ~Demo() { //destructor Console.WriteLine("Object is being deleted"); }
让我们看一个示例来学习如何在 C# 中使用析构函数。
示例
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(); // set line length line.setLength(6.0); Console.WriteLine("Length of line : {0}", line.getLength()); } } }
输出
Object is being created Length of line : 6 Object is being deleted
广告