Posted on 2009-08-03 13:45
Hero 閱讀(173)
評論(0) 編輯 收藏 引用 所屬分類:
C#積累
1 using System;
2 using System.Collections.Generic;
3 using System.Text;
4
5 namespace MyCollections
6 {
7 using System.Collections;
8
9 //聲明委托
10 public delegate void ChangedEventHandler( object sender, EventArgs e ) ;
11
12 //創(chuàng)建一個新類,每次列表更改時發(fā)送通知
13 public class ListWithChangedEvent : ArrayList
14 {
15 //聲明一個事件 -- 每當(dāng)元素列表更改時,客戶端可以利用該事件獲得通知
16 public event ChangedEventHandler Changed;
17
18 //調(diào)用Changed事件 -- 每當(dāng)列表更改時調(diào)用
19 protected virtual void OnChanged( EventArgs e )
20 {
21 if ( Changed != null ) Changed( this, e );
22 }
23
24 //重寫可更改列表的某些方法 -- 在每個重寫后調(diào)用事件 -- 面向?qū)ο蟮膬?yōu)點(易于擴展)
25 public override int Add( object value )
26 {
27 int reval = base.Add( value );
28 OnChanged( EventArgs.Empty );
29 return reval;
30 }
31
32 public override void Clear()
33 {
34 base.Clear();
35 OnChanged( EventArgs.Empty );
36 }
37
38 public override object this[int index]
39 {
40 get
41 {
42 return base[index];
43 }
44 set
45 {
46 base[index] = value;
47 OnChanged( EventArgs.Empty );
48 }
49 }
50 }
51 }
52
53 namespace TestEvents
54 {
55 using MyCollections;
56
57 class EventListener
58 {
59 private ListWithChangedEvent List;
60
61 public EventListener( ListWithChangedEvent _list )
62 {
63 this.List = _list;
64 //將“ListChanged”添加到“List”中的Changed事件
65 this.List.Changed +=new ChangedEventHandler(List_Changed);
66 }
67
68 //每當(dāng)列表更改時進(jìn)行以下調(diào)用 -- 事件我們自己寫
69 public void List_Changed( object sender, EventArgs e )
70 {
71 Console.WriteLine( "This is called when event fires." );
72 }
73
74 public void Detach()
75 {
76 //分離事件并刪除列表
77 this.List.Changed -= new ChangedEventHandler( List_Changed );
78 this.List = null;
79 }
80 }
81 }
82
83 namespace Event2
84 {
85 using MyCollections;
86 using TestEvents;
87
88 class Program
89 {
90 static void Main( string[] args )
91 {
92 //創(chuàng)建新列表
93 ListWithChangedEvent list = new ListWithChangedEvent();
94 //創(chuàng)建一個類,用于偵聽列表的更改事件
95 EventListener listener = new EventListener( list );
96
97 list.Add( "wang" );
98 list.Clear();
99
100 listener.Detach();
101 }
102 }
103 }
104