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

ความแตกต่างระหว่าง Constructor และ Destructor ใน C# คืออะไร

Constructor (ตัวสร้าง)

Constructor ของคลาสเป็นฟังก์ชันสมาชิกพิเศษที่จะทำงานทุกครั้งที่เราสร้างออบเจ็กต์ใหม่ของคลาสนั้น

Constructor มีชื่อเหมือนกับชื่อคลาสพอดี และไม่มีประเภทการคืนค่า (return type)

ตัวอย่างโครงสร้าง Constructor:

class Demo {    public Demo() {} }

ตัวอย่างการใช้งาน Constructor

using System; 
namespace LineApplication { 
    class Line { 
        private double length; // ความยาวของเส้น 
        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(); 
            // กำหนดความยาวเส้น 
            line.setLength(6.0); 
            Console.WriteLine("Length of line : {0}", line.getLength()); 
            Console.ReadKey(); 
        } 
    } 
}

ผลลัพธ์

Object is being created Length of line : 6

Destructor (ตัวทำลาย)

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

ชื่อ Destructor เหมือนชื่อคลาสแต่อยู่หน้าด้วยเครื่องหมายทิลเด (~)

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

ตัวอย่างการใช้งาน Destructor

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