डेलीगेट (Delegate) एक टाइप-सेफ फंक्शन पॉइंटर है जो मेथड का रेफरेंस रखता है। रनटाइम पर मेथड बदला जा सकता है। इवेंट्स और कॉलबैक्स का आधार।
घोषणा
delegate;
पूर्ण उदाहरण
using System;
using System.IO;
namespace DelegateAppl
{
class PrintString
{
static FileStream fs;
static StreamWriter sw;
// डेलीगेट घोषणा
public delegate void PrintStringDelegate(string s);
// कंसोल पर प्रिंट
public static void WriteToScreen(string str)
{
Console.WriteLine("स्ट्रिंग है: {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(PrintStringDelegate ps)
{
ps("Hello World");
}
static void Main(string[] args)
{
PrintStringDelegate ps1 = new PrintStringDelegate(WriteToScreen);
PrintStringDelegate ps2 = new PrintStringDelegate(WriteToFile);
SendString(ps1);
SendString(ps2);
Console.ReadKey();
}
}
}
आउटपुट
स्ट्रिंग है: Hello World
(और फाइल में "Hello World" लिखा जाता है)
मुख्य बिंदु
- सभी डेलीगेट्स
System.Delegateसे अंतर्निहित रूप से डेराइव्ड। - मल्टीकास्ट डेलीगेट:
del += Method1; del += Method2; del()दोनों कॉल करता है। Func<T, TResult>,Action<T>,Predicate<T>बिल्ट-इन जेनेरिक डेलीगेट्स।- लैम्ब्डा एक्सप्रेशन:
Funcadd = (x, y) => x + y; - कोवेरिएंस/कंट्रावेरिएंस:
Func<out TResult>,Action<in T>।