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.