EventHandler 委托

EventHandler 委托

定义

表示将用于处理不具有事件数据的事件的方法。

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

参数

sender
Object

事件源。

e
EventArgs

不包含事件数据的对象。

示例

以下示例演示与委托关联的EventHandler名为 ThresholdReached 的事件。 分配给委托的方法 EventHandler 在 方法中 OnThresholdReached 调用。

C#
using System;

namespace ConsoleApplication3
{
    public class Program3
    {
        public static void Main()
        {
            Counter c = new(new Random().Next(10));
            c.ThresholdReached += c_ThresholdReached;

            Console.WriteLine("press 'a' key to increase total");
            while (Console.ReadKey(true).KeyChar == 'a')
            {
                Console.WriteLine("adding one");
                c.Add(1);
            }
        }

        static void c_ThresholdReached(object? sender, ThresholdReachedEventArgs e)
        {
            Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold,  e.TimeReached);
            Environment.Exit(0);
        }
    }

    class Counter
    {
        private readonly int _threshold;
        private int _total;

        public Counter(int passedThreshold)
        {
            _threshold = passedThreshold;
        }

        public void Add(int x)
        {
            _total += x;
            if (_total >= _threshold)
            {
                ThresholdReachedEventArgs args = new()
                {
                    Threshold = _threshold,
                    TimeReached = DateTime.Now
                };
                OnThresholdReached(args);
            }
        }

        protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
        {
            ThresholdReached?.Invoke(this, e);
        }

        public event EventHandler<ThresholdReachedEventArgs>? ThresholdReached;
    }

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

注解

.NET Framework中的事件模型基于具有将事件与其处理程序连接的事件委托。 若要引发事件,需要两个元素:

  • 一个委托,它标识为事件提供响应的方法。

  • (可选)一个保存事件数据的类(如果事件提供数据)。

委托是定义签名的类型,即方法的返回值类型和参数列表类型。 可以使用委托类型声明一个变量,该变量可以引用与委托具有相同签名的任何方法。

事件处理程序委托的标准签名定义不返回值的方法。 此方法的第一个参数的类型为 Object ,引用引发事件的实例。 其第二个参数派生自 类型 EventArgs 并保存事件数据。 如果事件不生成事件数据,则第二个参数只是 字段的值 EventArgs.Empty 。 否则,第二个参数是派生自 EventArgs 的类型,并提供保存事件数据所需的任何字段或属性。

委托 EventHandler 是预定义的委托,专门表示不生成数据的事件的事件处理程序方法。 如果事件确实生成了数据,则必须使用泛型 EventHandler<TEventArgs> 委托类。

若要将事件与将处理事件的方法相关联,请将 委托的实例添加到 事件。 除非移除了该委托,否则每当发生该事件时就会调用事件处理程序。

有关事件处理程序委托的详细信息,请参阅 处理和引发事件

posted on 2025-04-06 12:41  漫思  阅读(10)  评论(0)    收藏  举报

导航