ผู้รับมอบสิทธิ์ C# นั้นคล้ายกับตัวชี้ไปยังฟังก์ชันใน C หรือ C++ ผู้รับมอบสิทธิ์คือตัวแปรประเภทการอ้างอิงที่เก็บการอ้างอิงถึงวิธีการ การอ้างอิงสามารถเปลี่ยนแปลงได้ที่รันไทม์
ไวยากรณ์สำหรับการประกาศผู้รับมอบสิทธิ์ -
delegate <return type> <delegate-name> <parameter list>
ให้เรามาดูวิธีการยกตัวอย่างตัวแทนใน C#
เมื่อมีการประกาศประเภทผู้รับมอบสิทธิ์ จะต้องสร้างวัตถุผู้รับมอบสิทธิ์ด้วยคำหลักใหม่และเชื่อมโยงกับวิธีการเฉพาะ เมื่อสร้างผู้รับมอบสิทธิ์ อาร์กิวเมนต์ที่ส่งไปยังนิพจน์ใหม่จะถูกเขียนคล้ายกับการเรียกเมธอด แต่ไม่มีอาร์กิวเมนต์ของเมธอด
public delegate void printString(string s); ... printString ps1 = new printString(WriteToScreen); printString ps2 = new printString(WriteToFile);
ต่อไปนี้คือตัวอย่างการประกาศและยกตัวอย่างตัวแทนใน C# -
ตัวอย่าง
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) { //create delegate instances NumberChanger nc1 = new NumberChanger(AddNum); NumberChanger nc2 = new NumberChanger(MultNum); //calling the methods using the delegate objects nc1(25); Console.WriteLine("Value of Num: {0}", getNum()); nc2(5); Console.WriteLine("Value of Num: {0}", getNum()); Console.ReadKey(); } } }
ผลลัพธ์
Value of Num: 35 Value of Num: 175