二.定義委托及事件
public delegate void MailMsgEventHandler(object sender,MailMsgEventArgs e);
public event MailMsgEventHandler MailMsg;
完整代碼定義如下:
1namespace EventEmail
三 .傳真和手機的定義:
2{
3 //定義一委托
4 public delegate void MailMsgEventHandler(object sender,MailMsgEventArgs e);
5
6 public class MailManager
7 {
8 public event MailMsgEventHandler MailMsg; //委托類型的事件
9
10 protected virtual void OnMailMsg(MailMsgEventArgs e)
11 {
12 if (this.MailMsg != null)
13 {
14 MailMsg(this, e);
15 }
16 }
17
18 //通過事件傳遞消息
19 public void SimulateArrivingMsg(string from, string to, string subject, string body)
20 {
21 MailMsgEventArgs e = new MailMsgEventArgs(from, to, subject, body);
22 OnMailMsg(e);
23 }
24 }
25}
1namespace EventEmail
2{
3 /**//// <summary>
4 /// 傳真機
5 /// </summary>
6 public class Fax
7 {
8 private TextBox _tBox;
9 public Fax(MailManager mm, TextBox tBox)
10 {
11 //監聽事件
12 //這裡的FaxMsg,指的是符合MailMsgEventHandler委托的方法,也就是激發事件後所 執行的方法
13 mm.MailMsg += new MailMsgEventHandler(FaxMsg);
14 _tBox = tBox;
15 }
16
17 private void FaxMsg(Object sender, MailMsgEventArgs e)
18 {
19 _tBox.Text += string.Format("消息到傳真:{4}來自:{0}{4}發到:{1}{4}主題:{2} {4}內容:{3}{4}{4}", e.from, e.to, e.subject, e.body, Environment.NewLine);
20 }
21
22 public void Register(MailManager mm)
23 {
24 mm.MailMsg += new MailMsgEventHandler(FaxMsg);
25 }
26
27 public void UnRegister(MailManager mm)
28 {
29 //注銷事件
30 mm.MailMsg -= new MailMsgEventHandler(FaxMsg);
31 }
32 }
33}
---------------------------------------------------------------------------------------- -------------------