Một delegate trong C# là tham chiếu đến phương thức. Delegate là biến kiểu tham chiếu giữ tham chiếu đến một phương thức. Tham chiếu có thể thay đổi tại runtime.
Delegate đặc biệt được dùng để triển khai sự kiện (events) và phương thức call-back. Tất cả delegate đều được kế thừa ngầm từ lớp System.Delegate.
Hãy xem cách khai báo delegate trong C#.
delegate
Hãy xem ví dụ để học cách làm việc với Delegate trong C#.
Ví dụ
using System;
using System.IO;
namespace DelegateAppl {
class PrintString {
static FileStream fs;
static StreamWriter sw;
// khai báo delegate
public delegate void printString(string s);
// phương thức này in ra console
public static void WriteToScreen(string str) {
Console.WriteLine("Chuỗi là: {0}", str);
}
// phương thức này in 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();
}
// phương thức này nhận delegate làm tham số và dùng nó để
// gọi các phương thức khi cần
public static void sendString(printString ps) {
ps("Hello World");
}
static void Main(string[] args) {
printString ps1 = new printString(WriteToScreen);
printString ps2 = new printString(WriteToFile);
sendString(ps1);
sendString(ps2);
Console.ReadKey();
}
}
}
Kết quả
Chuỗi là: Hello World