标签:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 6 namespace ClassTrining 7 { 8 class 事件 9 { 10 class Demo 11 { 12 /// <summary> 13 /// 实例化事件处理类并测试事件 14 /// </summary> 15 /// <param name="args"></param> 16 static void Test(string[] args) 17 { 18 //实例化事件处理类对象 19 Counter c = new Counter(new Random().Next(10)); 20 //添加事件 21 c.ThresholdReached += c_ThresholdReached; 22 23 Console.WriteLine("press ‘a‘ key to increase total"); 24 while (Console.ReadKey(true).KeyChar == ‘a‘) 25 { 26 Console.WriteLine("adding one"); 27 c.Add(1); 28 } 29 } 30 /// <summary> 31 /// 实例事件处理方法 32 /// </summary> 33 /// <param name="sender">事件来源对象</param> 34 /// <param name="e">事件数据对象</param> 35 static void c_ThresholdReached(object sender, ThresholdReachedEventArgs e) 36 { 37 Console.WriteLine("The threshold of {0} was reached at {1}.", e.Threshold, e.TimeReached); 38 Environment.Exit(0); 39 } 40 } 41 42 /// <summary> 43 /// 事件处理类 44 /// </summary> 45 class Counter 46 { 47 private int threshold; 48 private int total; 49 50 public Counter(int passedThreshold) 51 { 52 threshold = passedThreshold; 53 } 54 55 public void Add(int x) 56 { 57 total += x; 58 if (total >= threshold) 59 { 60 //声明事件数据 61 ThresholdReachedEventArgs args = new ThresholdReachedEventArgs(); 62 args.Threshold = threshold; 63 args.TimeReached = DateTime.Now; 64 //调用虚函数处理事件数据 65 OnThresholdReached(args); 66 } 67 } 68 /// <summary> 69 /// 虚方法,可以被子类重载 70 /// </summary> 71 /// <param name="e"></param> 72 protected virtual void OnThresholdReached(ThresholdReachedEventArgs e) 73 { 74 //泛型事件委托 75 EventHandler<ThresholdReachedEventArgs> handler = ThresholdReached; 76 if (handler != null) 77 { 78 //this代表事件来源,e代表不包含事件数据的对象 79 handler(this, e); 80 } 81 } 82 /// <summary> 83 /// 事件委托方法 84 /// </summary> 85 public event EventHandler<ThresholdReachedEventArgs> ThresholdReached; 86 } 87 88 /// <summary> 89 /// 处理事件数据类 90 /// </summary> 91 public class ThresholdReachedEventArgs : EventArgs 92 { 93 public int Threshold { get; set; } 94 public DateTime TimeReached { get; set; } 95 } 96 } 97 }
标签:
原文地址:http://www.cnblogs.com/linhongquan/p/5470667.html