给出一个应用EventHandler的简单例子
时间: 2024-05-02 07:17:10 浏览: 8
下面是一个使用EventHandler的简单例子:
```csharp
using System;
public class Program
{
public static void Main()
{
// 创建一个事件源对象
EventSource eventSource = new EventSource();
// 创建一个事件处理器对象
EventHandler eventHandler = new EventHandler();
// 将事件处理器注册到事件源的事件中
eventSource.SomeEvent += eventHandler.HandleEvent;
// 触发事件
eventSource.RaiseEvent();
}
}
// 事件源类
public class EventSource
{
// 定义一个事件
public event EventHandler SomeEvent;
// 触发事件
public void RaiseEvent()
{
// 如果事件有注册处理器,则触发事件
if (SomeEvent != null)
{
SomeEvent(this, EventArgs.Empty);
}
}
}
// 事件处理器类
public class EventHandler
{
// 事件处理方法
public void HandleEvent(object sender, EventArgs args)
{
Console.WriteLine("事件被触发了!");
}
}
```
上面的代码中,我们创建了一个事件源对象 `EventSource` 和一个事件处理器对象 `EventHandler`,并将事件处理器注册到事件源对象的事件 `SomeEvent` 中。当我们调用事件源对象的 `RaiseEvent` 方法时,如果事件有注册处理器,则事件处理器会被触发,输出一条信息。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)