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.