c# event

Overview:

An event in C# is a special kind of delegate that is used to implement the observer pattern, allowing objects to notify other objects when a specific event occurs.
Insert image description here

Here is an example using C# events:

First, define a class that contains events:

public class EventPublisher
{
    
    
    // 声明一个事件(默认使用的EventArgs类型的参数,可以定义自己的参数类型)
    // public class MyArgs 
    //{
    
    
        // public int id;
        // public string name;
       //}
     //public event EventHandler<MyArgs> onatack = null;
    public event EventHandler MyEvent;

    // 触发事件的方法
    public void RaiseEvent()
    {
    
    
        // 检查是否有订阅者
        if (MyEvent != null)
        {
    
    
            // 创建并传递事件参数
            MyEvent(this, EventArgs.Empty);
        }
    }
}

In the above code, we have defined an EventPublisher class which contains an event named MyEvent. This event is based on the EventHandler delegate type, which accepts two parameters: the sender of type object and the event parameter of type EventArgs.

Next, create a class that subscribes to events:

public class EventSubscriber
{
    
    
    // 事件处理方法
    public void HandleEvent(object sender, EventArgs e)
    {
    
    
        Console.WriteLine("事件被触发!");
    }
}

In the above code, we have created an EventSubscriber class and defined a method called HandleEvent in it, which acts as an event handler.

Finally, use events and subscribers in the main program:

EventPublisher publisher = new EventPublisher();
EventSubscriber subscriber = new EventSubscriber();

// 订阅事件
publisher.MyEvent += subscriber.HandleEvent;

// 触发事件
publisher.RaiseEvent();

Running the program will output the following results:

事件被触发!

In this example, we create an EventPublisher object and an EventSubscriber object. Then, we subscribe the subscriber.HandleEvent method to the publisher.MyEvent event. Finally, we trigger the event by calling the publisher.RaiseEvent method.

When the event is triggered, the subscribed method HandleEvent will be executed to implement the corresponding operation on the event.

By using events, loose coupling between objects can be achieved, and one object can subscribe to the events of another object without knowing the specific implementation details. This makes the code easier to maintain and extend

Guess you like

Origin blog.csdn.net/qq_41942413/article/details/132628789