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

Cách khai báo delegate trong C#?

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 dùng để triển khai sự kiện (events) và phương thức gọi lại (call-back methods). Tất cả delegate đều ngầm kế thừa từ lớp System.Delegate.

Hãy xem cách khai báo delegate trong C#:

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

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("The String is: {0}", str); 
        } 
        // phương thức này in vào tệp 
        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 lấy 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ả

The String is: Hello World