C#的事件处理机制
今天,花费了一下午事件,终于算是了解了事件的处理机制。在C#中,对于事件的应用其实可以有四个步骤。
1.在事件发行者中定义一个事件
2.在事件发行者触发事件
3.在事件订阅者中处理事件的处理程序
4.向事件发行者订阅事件。
一个简单的例子,老公发工资了,老婆、儿子会自动获得他的工资,呵呵!
![](https://www.cnblogs.com/Images/OutliningIndicators/ExpandedBlockStart.gif)
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace ConsoleApplication1
6 {
7 class SalaryEvent : EventArgs //工资发放事件,继承子EventArgs
8 {
9 private readonly double mySalary;
10 private readonly DateTime issuDate;
11 public double MySalary
12 {
13 get { return mySalary; }
14 }
15 public DateTime IssuDate
16 {
17 get { return issuDate; }
18 }
19 public SalaryEvent(double _mySalary, DateTime _issudate)
20 {
21 mySalary = _mySalary;
22 issuDate = _issudate;
23 }
24 }
25 public delegate void SalaryMeEventHandler(object sender, SalaryEvent e); //定义一个工资发放委托
26 class Salary
27 {
28 public Salary() { }
29 public event SalaryMeEventHandler SalaryMe;//通过委托定义一个工资发放事件
30 protected virtual void onSalary(SalaryEvent e)
31 {
32 SalaryMeEventHandler salaryHander = SalaryMe;
33 if (salaryHander != null)
34 {
35
36 SalaryMe(this,e); //真正的触发事件
37 }
38 }
39 public void issueSalary(double snum,DateTime stime) //生成SalaryEvent对象,用于接受数据
40 {
41 SalaryEvent sEvent=new SalaryEvent(snum,stime);
42 Console.WriteLine("今天是"+stime.ToString()+"我发工资了,金额为"+snum.ToString()+"元");
43 onSalary(sEvent);
44 }
45
46
47
48 }
49 class MyWife
50 {
51
52 public void getHunsbandSalary(object sender,SalaryEvent e) //定义妻子类的事件处理程序
53 {
54 Console.WriteLine("老公发工资了,我可以有{0}块钱买衣服了!",e.MySalary*0.7);
55
56 }
57 }
58 class MySon
59 {
60 public void getFatherSalary(object sender, SalaryEvent e)//定义儿子类的事件处理程序
61 {
62 Console.WriteLine("老爸发工资了,我可以有{0}块钱买玩具了!",e.MySalary*0.2);
63 }
64 }
65 class Me
66 {
67 public void getMySalary(object sender, SalaryEvent e)//定义自己的事件处理程序
68 {
69 Console.WriteLine("老婆,儿子都分完了,我只剩{0}块钱了!",e.MySalary*0.1);
70 }
71 }
72 class Test
73 {
74 static void Main()
75 {
76 Salary salary = new Salary();
77 MyWife wife=new MyWife();
78 MySon son = new MySon();
79 Me me = new Me();
80 salary.SalaryMe += new SalaryMeEventHandler( wife.getHunsbandSalary);//注册事件
81 salary.SalaryMe += new SalaryMeEventHandler(son.getFatherSalary);//注册事件
82 salary.SalaryMe += new SalaryMeEventHandler(me.getMySalary);//注册事件
83 salary.issueSalary(2100, Convert.ToDateTime("2008-9-15"));
84
85 }
86 }
87 }
88
89