什么是 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 次浏览量

开启您的 职业 生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.