什么是 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
广告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP