官方注解:
.NET Framework 中的事件模型基于事件委托,该委托将事件与其处理程序连接。 若要引发事件,需要两个元素:
-
一个委托,该委托标识向事件提供响应的方法。
-
如果事件提供数据,则为包含事件数据的类(可选)。
委托是一种类型,它定义签名,即方法的返回值类型和参数列表类型。 您可以使用委托类型声明一个变量,该变量可引用具有与委托相同的签名的任何方法。
事件处理程序委托的标准签名定义不返回值的方法。 此方法的第一个参数的类型为 Object,并引用引发事件的实例。 它的第二个参数派生自类型 EventArgs,并保存事件数据。 如果事件不生成事件数据,第二个参数就是 EventArgs.Empty 字段的值。 否则,第二个参数是从 EventArgs 派生的类型,并提供保存事件数据所需的任何字段或属性。
EventHandler 委托是一个预定义的委托,它专门表示不生成数据的事件的事件处理程序方法。 如果事件确实生成了数据,则必须使用泛型 EventHandler<TEventArgs> 委托类。
若要将事件与将处理事件的方法相关联,请将委托的实例添加到事件。 除非移除了该委托,否则每当发生该事件时就会调用事件处理程序。
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello Event!");
Counter c = new Counter(new Random().Next(10));
Console.WriteLine($"临界值为:{c.GetThreshold()}");
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 async void c_ThresholdReached(object sender, ThresholdReachedEventArgs e)
{
Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached);
Console.WriteLine("exit coming soon...");
await Task.Delay(3000);
Environment.Exit(0);
}
}

public class Counter
{
private int threshold;
private int total;
public Counter(int passedThreshold)
{
threshold = passedThreshold;
}
public int GetThreshold() => this.threshold;
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(this, e);
}
}
public event EventHandler<ThresholdReachedEventArgs> ThresholdReached;
}
public class ThresholdReachedEventArgs : EventArgs
{
public int Threshold { get; set; }
public DateTime TimeReached { get; set; }
}

执行结果:

网友评论