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-Jun-2020

429 次浏览

开启您的 职业生涯

完成课程,获得认证

开始
广告
© . All rights reserved.