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

Hàm hủy (Destructor) trong chương trình C#

Destructor là phương thức đặc biệt của class, thực thi khi đối tượng đi ra khỏi phạm vi (out of scope) hoặc bị Garbage Collector thu gom.

  • Trùng tên class nhưng có tiền tố ~ (tilde).
  • Không có tham số, không có access modifier.
  • Không thể gọi trực tiếp, không thể overload.
  • Chỉ có tối đa 1 destructor mỗi class.

Cú pháp:

public Demo() { Console.WriteLine("Object created"); }  // Constructor
~Demo() { Console.WriteLine("Object deleted"); }        // Destructor

Ví dụ

using System;

namespace LineApplication
{
    class Line
    {
        private double length;
        
        public Line() { Console.WriteLine("Object is being created"); }
        ~Line() { 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());
            // Destructor gọi khi line ra khỏi scope hoặc GC collect
        }
    }
}

Kết quả

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

Lưu ý quan trọng: C# có Garbage Collector tự động quản lý bộ nhớ. Destructor (finalizer) chạy không xác định (non-deterministic) khi GC thu gom. Để giải phóng tài nguyên không quản lý (file handle, DB connection...), triển khai interface IDisposable và pattern Dispose() (using statement).