Events क्या हैं
एक event किसी doorbell जैसा है: जब कुछ होता है, सुनने के लिए sign up किए सभी को बता दिया जाता है। Sender को यह जानने की ज़रूरत नहीं कि कौन सुन रहा है।
In this page:
Syntax
class Publisher
{
public event Action EventName;
public void Raise()
{
EventName?.Invoke();
}
}
publisher.EventName += HandlerMethod; // subscribe
Events
एक event एक delegate-based member है जो publish/subscribe pattern का पालन करता है — कोई class event raise करती है, और कोई भी संख्या में external handlers इस पर react करने के लिए subscribe कर सकते हैं, बिना publisher को यह जाने कि वे कौन हैं।
Subscribers += से attach होते हैं और class इसे एक delegate की तरह invoke करके internally event raise करती है। Events वह तरीका है जिससे UI frameworks और कई libraries code को state changes के बारे में notify करती हैं।
Note:
किसी
event को सिर्फ अपनी declaring class के अंदर से raise किया जा सकता है, भले ही बाहर का code इसे subscribe कर सके।उदाहरण: Events
using System;
class Button
{
public event Action Clicked;
public void Click()
{
Console.WriteLine("Button clicked!");
Clicked?.Invoke();
}
}
class Program
{
static void Main(string[] args)
{
Button button = new Button();
button.Clicked += () => Console.WriteLine("Handler: something happened");
button.Click();
}
}
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. #}
आम गलतियां
- subscribers जांचे बिना एक event raise करना, जिससे एक null event throw करता है;
Event?.Invoke(...)का उपयोग करें। - इसे declare करने वाली class के बाहर से एक event raise करने की कोशिश करना, जो एक compile error है।
-=से unsubscribe करना भूल जाना, जो objects को जीवित रख सकता है और memory leaks का कारण बन सकता है।
🔒
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: