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

Cách khai báo và khởi tạo Delegate trong C#

Delegate trong C# tương tự con trỏ hàm (function pointer) trong C/C++. Delegate là biến kiểu tham chiếu lưu trữ tham chiếu đến một phương thức. Tham chiếu có thể thay đổi tại runtime.

Cú pháp khai báo:

delegate <return type> <delegate-name> <parameter list>;

Khởi tạo (Instantiate) delegate:

Sau khi khai báo kiểu delegate, tạo đối tượng delegate với new và gán phương thức mục tiêu:

public delegate void PrintString(string s);
// ...
PrintString ps1 = new PrintString(WriteToScreen);
PrintString ps2 = new PrintString(WriteToFile);

Ví dụ hoàn chỉnh

using System;

delegate int NumberChanger(int n);

namespace DelegateAppl
{
    class TestDelegate
    {
        static int num = 10;
        
        public static int AddNum(int p) { num += p; return num; }
        public static int MultNum(int q) { num *= q; return num; }
        public static int GetNum() { return num; }
        
        static void Main(string[] args)
        {
            // Tạo instance delegate
            NumberChanger nc1 = new NumberChanger(AddNum);
            NumberChanger nc2 = new NumberChanger(MultNum);
            
            // Gọi qua delegate
            nc1(25);
            Console.WriteLine("Value of Num: {0}", GetNum()); // 35
            
            nc2(5);
            Console.WriteLine("Value of Num: {0}", GetNum()); // 175
            Console.ReadKey();
        }
    }
}

Kết quả

Value of Num: 35
Value of Num: 175

Lưu ý: Delegate là nền tảng của event và callback. C# 2.0+ hỗ trợ anonymous method, C# 3.0+ hỗ trợ lambda expression (() => ...) ngắn gọn hơn new Delegate(Method).