Delegate trong C# là tham chiếu đến một phương thức. Là biến kiểu tham chiếu lưu trữ tham chiếu phương thức, có thể thay đổi tại runtime.
Delegate đặc biệt dùng cho: event và callback methods. Tất cả delegate ngầm kế thừa từ System.Delegate.
Khai báo delegate:
delegate <return type> <delegate-name> <parameter list>;
Ví dụ: Delegate in ra màn hình và ghi file
using System;
using System.IO;
namespace DelegateAppl
{
class PrintString
{
static FileStream fs;
static StreamWriter sw;
// Delegate declaration
public delegate void PrintStringDelegate(string s);
// Method 1: In ra console
public static void WriteToScreen(string str)
{
Console.WriteLine("The String is: {0}", str);
}
// Method 2: Ghi vào file
public static void WriteToFile(string s)
{
fs = new FileStream("c:\\message.txt", FileMode.Append, FileAccess.Write);
sw = new StreamWriter(fs);
sw.WriteLine(s);
sw.Flush(); sw.Close(); fs.Close();
}
// Method nhận delegate làm tham số
public static void SendString(PrintStringDelegate ps)
{
ps("Hello World");
}
static void Main(string[] args)
{
PrintStringDelegate ps1 = new PrintStringDelegate(WriteToScreen);
PrintStringDelegate ps2 = new PrintStringDelegate(WriteToFile);
SendString(ps1);
SendString(ps2);
Console.ReadKey();
}
}
}
Kết quả
The String is: Hello World
(Và file c:\message.txt chứa "Hello World")
Hiện đại: Dùng Action, Func, Predicate (built-in delegates) và lambda () => ... thay vì khai báo delegate tùy chỉnh.