Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Khác biệt giữa Constructor và Destructor trong C#

Constructor (Hàm khởi tạo)

Constructor là member function đặc biệt của class thực thi khi tạo object mới của class đó.

Constructor có tên trùng tên class và KHÔNG có kiểu trả về.

Constructor tên trùng class:

class Demo { 
    public Demo() {} 
}

Ví dụ:

Ví dụ

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(); 
        } 
    } 
}

Kết quả

Object is being created
Length of line : 6

Destructor (Hàm hủy)

Destructor là member function đặc biệt thực thi khi object của class đó ra khỏi scope. Không trả về giá trị cũng không nhận tham số.

Tên trùng class với tiền tố tilde (~):

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

Ví dụ làm việc với Destructors:

Ví dụ

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()); 
        } 
    } 
}

Kết quả

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