C# में डेलीगेट मेथड का रेफरेंस होता है। एक डेलीगेट एक रेफरेंस टाइप वेरिएबल है जो एक मेथड का रेफरेंस रखता है। रेफरेंस को रनटाइम पर बदला जा सकता है।
डेलीगेट्स विशेष रूप से इवेंट्स और कॉल-बैक मेथड्स को लागू करने के लिए उपयोग किए जाते हैं। सभी डेलीगेट्स अप्रत्यक्ष रूप से System.Delegate क्लास से डेराइव्ड होते हैं।
आइए देखें कि C# में डेलीगेट्स कैसे घोषित करें।
delegate <रिटर्न टाइप> <डेलीगेट-नाम> <पैरामीटर सूची>
आइए C# में डेलीगेट्स के साथ काम करना सीखने के लिए एक उदाहरण देखें।
उदाहरण
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