EventHandler क्या है
EventHandler .NET में events के लिए standard shape है, जैसे एक standard form जो सब एक जैसे तरीके से भरते हैं। यह बताता है कि event किसने भेजा और कोई अतिरिक्त details।
In this page:
Syntax
class DataEventArgs : EventArgs
{
public type Data;
}
public event EventHandler<DataEventArgs> EventName;
EventName?.Invoke(this, new DataEventArgs { Data = value });
void Handler(object sender, DataEventArgs e) { }
EventHandler
EventHandler और EventHandler<TEventArgs> events के लिए standard .NET delegate types हैं, एक sender object और एक EventArgs-derived parameter के convention का पालन करते हुए।
इनका उपयोग आपके events को बाकी .NET ecosystem के साथ consistent रखता है। TEventArgs आमतौर पर जो हुआ उसके बारे में अतिरिक्त data रखता है।
Note:
Custom event data classes को
EventArgs से inherit करना चाहिए, convention के अनुसार "EventArgs" पर खत्म होने वाला नाम।उदाहरण: EventHandler
using System;
class PriceChangedEventArgs : EventArgs
{
public decimal NewPrice;
}
class Stock
{
public event EventHandler<PriceChangedEventArgs> PriceChanged;
public void UpdatePrice(decimal price)
{
PriceChanged?.Invoke(this, new PriceChangedEventArgs { NewPrice = price });
}
}
class Program
{
static void Main(string[] args)
{
Stock stock = new Stock();
stock.PriceChanged += (sender, e) => Console.WriteLine($"New price: {e.NewPrice}");
stock.UpdatePrice(101.5m);
}
}
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. #}
आम गलतियां
PriceChanged(this, args)से event raise करना जब कोई subscribe न हुआ हो, जो एकNullReferenceExceptionफेंकता है;PriceChanged?.Invoke(this, args)का उपयोग करें।stock.PriceChanged = handler;से इसकी class के बाहर से event assign या raise करने की कोशिश करना, जबकि बाहर का code सिर्फ+=और-=उपयोग कर सकता है।- गलत signature वाला एक handler लिखना, क्योंकि किसी
EventHandler<T>method को(object sender, T e)लेना चाहिए, और+=से subscribe करना भूल जाना जिससे कुछ नहीं होता।
चैप्टर सारांश
- Delegates methods के references रखते हैं, और multicast delegates कई methods call कर सकते हैं।
- Lambda expressions और
Func,Action, औरPredicateछोटे delegates लिखते हैं। - Events और
EventHandlerobjects को कुछ होने पर दूसरों को notify करने देते हैं।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: