C# 中的构造函数和析构函数有什么区别?


构造函数

类构造函数是类的特殊成员函数,每当我们创建该类的对象时都会执行该构造函数。

构造函数的名称与类的名称完全相同,并且没有任何返回类型。

构造函数名称与类名称相同 -

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();

         // set line length
         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();

         // 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

更新时间:20-6月-2020

433 浏览次数

职业生涯起航

完成课程获取认证

开始
广告
© . All rights reserved.