Delegates क्या हैं
एक delegate एक variable है जो एक method रखता है, जैसे एक phone contact जिसे आप बाद में call कर सकते हैं। यह आपको actions को objects की तरह पास करने देता है।
In this page:
Syntax
delegate ReturnType DelegateName(type parameter);
DelegateName variable = MethodName;
ReturnType result = variable(argument);
Delegates
एक delegate किसी method का एक type-safe reference है, आपको methods को values की तरह पास करने देते हुए — parameters, return values के रूप में, या variables में store करते हुए।
आप एक delegate type declare करते हैं जो describe करती है कि यह किस method signature को point कर सकता है, फिर कोई भी matching method इसे assign करते हैं। delegate को call करना चाहे यह वर्तमान में जो भी method reference करता हो उसे invoke करता है।
Note:
Delegates वह नींव हैं जिन पर lambda expressions,
Func<>/Action<>, और events सब बने हैं।उदाहरण: Delegates
using System;
delegate int Operation(int a, int b);
class Program
{
static int Add(int a, int b) => a + b;
static int Multiply(int a, int b) => a * b;
static void Main(string[] args)
{
Operation op = Add;
Console.WriteLine(op(3, 4));
op = Multiply;
Console.WriteLine(op(3, 4));
}
}
Login to try C/C++/Java/PHP code in the editor
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the
view already swaps in the hi_ translation fields (or blanks these
out if untranslated), so this renders correctly for both languages
without a lang_code check here. #}
आम गलतियां
- किसी null delegate को सीधे invoke करना, जो
NullReferenceExceptionफेंकता है;?.Invokeका उपयोग करें। - किसी ऐसे method को assign करना जिसका signature delegate type से मेल न खाए, जो एक compile error है।
Method()से method को call करने कोMethodसे इसे पास करने के साथ confuse करना।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: