Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

Delegates (ตัวแทน) ใน C# คืออะไร

Delegate ใน C# คือการอ้างอิงไปยังเมธอด เป็นตัวแปรชนิดอ้างอิงที่เก็บ reference ไปยังเมธอด สามารถเปลี่ยน reference ได้ในขณะรันไทม์

Delegate ใช้โดยเฉพาะสำหรับ implement events และ callback methods ทุก delegate สืบทอดมาจาก System.Delegate โดยนัย

การประกาศ Delegate

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

ตัวอย่างเต็ม

using System;
using System.IO;

namespace DelegateAppl {
    class PrintString {
        static FileStream fs;
        static StreamWriter sw;
        
        public delegate void printString(string s);
        
        public static void WriteToScreen(string str) {
            Console.WriteLine("The String is: {0}", str);
        }
        
        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();
        }
        
        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();
        }
    }
}

ผลลัพธ์

The String is: Hello World