C# 程式中的解構函式是什麼?


解構函式是類的特殊成員函式,每當類的物件超出作用域時該函式就會被執行。

它與類名完全相同,只是前面加上了波浪號 (~),例如我們的類名為 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

2K+ 瀏覽量

啟動你的 職業生涯

完成課程,獲得認證

開始學習
廣告