事件简单例子

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Runtime.InteropServices;
 6 
 7 namespace EventTest
 8 {
 9     /// <summary>
10     /// 事件订阅者类
11     /// </summary>
12     class Program
13     {
14         static void Main(string[] args)
15         {
16             Counter c = new Counter(new Random().Next(10));
17             c.ThresholdReached += c_ThresholdReached;  // 订阅事件(注册事件)
18 
19             Console.WriteLine("press 'a' key to increase total");
20             while(Console.ReadKey(true).KeyChar=='a')
21             {
22                 Console.WriteLine("adding one");
23                 c.Add(1);
24             }
25             Console.ReadLine();
26         }
27 
28         static void c_ThresholdReached(object sender, CounterEventArgs e) // 事件处理程序
29         {
30             Console.WriteLine("The threshold was reached And Value is {0}.",e.total);
31             //Environment.Exit(0);
32         }
33     }
34 
35     /// <summary>
36     /// 事件数据类
37     /// </summary>
38     public class CounterEventArgs : EventArgs
39     {
40         public int total;
41         public CounterEventArgs(int passedTotal)
42         {
43             total = passedTotal;
44         }
45     }
46 
47     /// <summary>
48     /// 事件发布者类 
49     /// </summary>
50     /// <remarks>
51     /// 功能:实现total值的不断增加。达到阈值时触发事件给出达到阈值的提示。
52     /// </remarks>
53     public class Counter
54     {
55         public event EventHandler<CounterEventArgs> ThresholdReached;  // 声明事件
56 
57         private int total;
58         private int threshold;
59         public Counter(int passedThreshold)
60         {
61             threshold = passedThreshold;
62         }
63 
64         public void Add(int x)
65         {
66             total += x;
67             if (total >= threshold) // 在每次增加值之后判断是否触发事件
68             {
69                 CounterEventArgs cEArgs = new CounterEventArgs(total);
70                 OnThresholdReached(cEArgs); // 传递事件数据给事件处理程序
71             }
72         }
73 
74         protected virtual void OnThresholdReached(CounterEventArgs e) // 触发事件
75         {
76             EventHandler<CounterEventArgs> handler = ThresholdReached;
77             if (handler != null)
78             {
79                 handler(this, e);
80             }
81         }
82     }
83 }

 

原文地址:https://www.cnblogs.com/niaomingjian/p/3764413.html