EventHandler 委托
定义
命名空间:
程序集:
System.Runtime.dll
表示将用于处理不具有事件数据的事件的方法。
C#复制
public delegate void EventHandler(object? sender, EventArgs e);
参数
sender
事件源。
e
不包含事件数据的对象。
EventHandler<TEventArgs> 委托
定义
命名空间:
程序集:
System.Runtime.dll
表示当事件提供数据时将处理该事件的方法。
C#复制
public delegate void EventHandler<TEventArgs>(object? sender, TEventArgs e);
类型参数
TEventArgs
事件生成的事件数据的类型。
参数
sender
事件源。
e
TEventArgs
包含事件数据的对象。
using System;
namespace _24EventHandler委托
{
class Program
{
static void Main(string[] args)
{
Counter c = new Counter(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 int threshold;
private int total;
public Counter(int passedThreshold)
{
threshold = passedThreshold;
}
public void Add(int x)
{
total += x;
if (total >= threshold)
{
ThresholdReachedEventArgs args = new ThresholdReachedEventArgs();
args.Threshold = threshold;
args.TimeReached = DateTime.Now;
OnThresholdReached(args);
}
}
protected virtual void OnThresholdReached(ThresholdReachedEventArgs e)
{
EventHandler<ThresholdReachedEventArgs> handler = ThresholdReached;
if (handler != null)
{
handler?.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> 类。
若要将事件与将处理事件的方法关联,请向事件添加委托的实例。 除非移除了该委托,否则每当发生该事件时就会调用事件处理程序。