参考:https://docs.microsoft.com/zh-cn/dotnet/standard/events/index?view=netframework-4.8

标题:处理和引发事件

 

本文介绍委托模型的主要组件、如何在应用程序中使用事件以及如何在你的代码中实现事件。

事件和路由事件概述。

活动

INotifyPropertyChanged 接口的类的成员。

委托在下一节中介绍。

派生类应始终调用基类的 OnEventName 方法,以确保注册的委托接收事件。

EventHandler 委托相关联并且由 OnThresholdReached 方法引发。

class Counter
{
    public event EventHandler ThresholdReached;

    protected virtual void OnThresholdReached(EventArgs e)
    {
        EventHandler handler = ThresholdReached;
        handler?.Invoke(this, e);
    }

    // provide remaining implementation for the class
}

 

委托

委托声明足以定义委托类。

Delegate 类。

这些委托没有返回类型值,并且接受两个参数(事件源的对象和事件数据的对象)。

委托人通过维护事件的已注册事件处理程序列表来充当引发事件的类的事件调度程序。

下面的示例说明如何声明 ThresholdReachedEventHandler 委托。

public delegate void ThresholdReachedEventHandler(object sender, ThresholdReachedEventArgs e);

 

事件数据

SerialDataReceivedEventArgs 类作为它的一个参数。

EventArgs 类作为一个参数。

通常,应使用与 .NET 相同的命名模式,并且事件数据类名称应以 EventArgs 结尾。

它包含特定于引发事件的属性。

public class ThresholdReachedEventArgs : EventArgs
{
    public int Threshold { get; set; }
    public DateTime TimeReached { get; set; }
}

事件处理程序

若当事件发生时收到通知,您的事件处理程序方法必须订阅该事件。

该方法订阅 ThresholdReached 事件。

class Program
{
    static void Main()
    {
        var c = new Counter();
        c.ThresholdReached += c_ThresholdReached;

        // provide remaining implementation for the class
    }

    static void c_ThresholdReached(object sender, EventArgs e)
    {
        Console.WriteLine("The threshold was reached.");
    }
}

 

静态和动态事件处理程序

事件。

引发多个事件

对于这些情况,.NET 提供一个事件属性,可以将其与选择的另一数据结构一起用于存储事件委托。

如何:使用事件属性处理多个事件。

 

相关文章:

  • 2022-12-23
  • 2021-09-13
  • 2021-09-04
  • 2021-10-01
  • 2022-12-23
  • 2021-12-11
  • 2021-06-08
猜你喜欢
  • 2021-08-31
  • 2022-12-23
  • 2021-11-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案