类构造函数是类的特殊成员函数,只要我们创建该类的新对象,该构造函数便会执行。
构造函数的名称与类的名称完全相同,并且没有任何返回类型。
构造函数具有与类名称相同的名称-
class Demo { public Demo() {} }
以下是一个例子-
using System; namespace LineApplication { class Line { private double length; // Length of a line public Line() { Console.WriteLine("Object is being created"); } 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()); Console.ReadKey(); } } }
输出结果
Object is being created Length of line : 6
析构函数是类的特殊成员函数,只要其类的对象超出范围就执行该析构函数,它既不能返回值,也不能采用任何参数。
它的名称与带有代字号(〜)的类的名称完全相同,例如,我们的类名为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(); //设置线长 line.setLength(6.0); Console.WriteLine("Length of line : {0}", line.getLength()); } } }
输出结果
Object is being created Length of line : 6 Object is being deleted