Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Destructors (ตัวทำลาย) ในโปรแกรม C#

Destructor เป็นเมธอดสมาชิกพิเศษของคลาส ที่ทำงานเมื่อออบเจ็กต์ของคลาสนั้นเลิกใช้งาน (out of scope)

ชื่อเหมือนคลาสแต่มี tilde (~) นำหน้า:

public Demo() {  // constructor
    Console.WriteLine("Object is being created");
}
~Demo() {  // destructor
    Console.WriteLine("Object is being deleted");
}

ตัวอย่าง

using System;

namespace LineApplication {
    class Line {
        private double length;
        
        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();
            line.setLength(6.0);
            Console.WriteLine("Length of line : {0}", line.getLength());
        }
    }
}

ผลลัพธ์

Object is being created
Length of line : 6
Object is being deleted