SoFunction
Updated on 2025-04-14

Specific use of C# EventHander

EventHandleris a special type of delegate used to handle events in programming, especially in object-oriented programming (delegate). An event is a way for an object to notify other objects when a particular action or situation occurs. andEventHandlerIt is a mechanism that allows you to define what code should be executed when this event occurs.

existC#middle,EventHandleris a predefined delegate, usually used for simple events without specific parameters or return values. Its definition is as follows:

public delegate void EventHandler(object sender, EventArgs e);

here,senderis the object that triggers the event, andeIt contains event dataEventArgsObject (or its derived class). With these two parameters, the event handler can understand which object triggered the event, and some additional information about the event.

When you want to define an event in a class, you can useeventKeywords andEventHandlerDelegation type. For example:

public class MyClass  
{  
    // Declare an event    public event EventHandler MyEvent;  
  
    // Method to trigger events    protected virtual void OnMyEvent(EventArgs e)  
    {  
        MyEvent?.Invoke(this, e);  
    }  
  
    // Call this method somewhere to trigger the event    public void DoSomething()  
    {  
        // ... Perform some operations ...        OnMyEvent(); // Trigger event, passing an empty EventArgs object    }  
}

Other classes can subscribe to this event and provide a method to handle it:

public class AnotherClass  
{  
    private MyClass myClassInstance;  
  
    public AnotherClass(MyClass myClassInstance)  
    {  
         = myClassInstance;  
         += MyClass_MyEvent; // Subscribe to events    }  
  
    private void MyClass_MyEvent(object sender, EventArgs e)  
    {  
        // When MyEvent is triggered, this method will be called        ("MyEvent was raised by " + sender);  
    }  
}

In this example, whenMyClassofDoSomethingThe method is called and triggeredMyEventDuring the event,AnotherClassInMyClass_MyEventThe method will be executed.

It should be noted thatEventHandlerIt's just a way to deal with events. In more complex scenarios, you may need to define a custom delegate type to be able to pass more event-related information. For example, you can define a delegate with a custom event parameter type to pass more specific data when an event is triggered.

Summarize

passEventHanderThis simple delegation generates an event, such as clicking on the mouse, and then the event occurs (the mouse is pressed), and the delegation that was previously bound to the event will be executed. The delegation can be broadcast

This is the end of this article about the specific use of C# EventHander. For more related C# EventHander content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!