.net 中的委托和事件(适合初学者,看后绝对会领会不少)
实际上我一开始也是对事件和委托有点模糊,就去找点资料看看,碰巧看到篇不错的文章,受益匪浅。
下面是我看后写的一个模仿单击事件。
1public class Button
2 {
3 public string name = "我是按钮";
4 public delegate void ClickEventHandler(Object sender ,ClickEventArgs e);
5 public event ClickEventHandler click;
6 public class ClickEventArgs : EventArgs
7 {
8 public readonly string name;
9 public ClickEventArgs(string name)
10 {
11 this.name = name;
12 }
13 }
14 public virtual void OnClick(ClickEventArgs e)
15 {
16 if (click != null)
17 {
18 click(this, e);
19 }
20 }
21 public void danji()
22 {
23 ClickEventArgs e = new ClickEventArgs(name);
24 OnClick(e);
25 }
26
27 }
28 public class task
29 {
30 public void OnClick(Object sender ,Button.ClickEventArgs e)
31 {
32 Console.WriteLine(e.name);
33 }
34 }
35 class ClickEvent
36 {
37 static void Main(string[] args)
38 {
39 Button btn = new Button();
40 btn.click += (new task()).OnClick;
41 btn.danji();
42 }
43 }
2 {
3 public string name = "我是按钮";
4 public delegate void ClickEventHandler(Object sender ,ClickEventArgs e);
5 public event ClickEventHandler click;
6 public class ClickEventArgs : EventArgs
7 {
8 public readonly string name;
9 public ClickEventArgs(string name)
10 {
11 this.name = name;
12 }
13 }
14 public virtual void OnClick(ClickEventArgs e)
15 {
16 if (click != null)
17 {
18 click(this, e);
19 }
20 }
21 public void danji()
22 {
23 ClickEventArgs e = new ClickEventArgs(name);
24 OnClick(e);
25 }
26
27 }
28 public class task
29 {
30 public void OnClick(Object sender ,Button.ClickEventArgs e)
31 {
32 Console.WriteLine(e.name);
33 }
34 }
35 class ClickEvent
36 {
37 static void Main(string[] args)
38 {
39 Button btn = new Button();
40 btn.click += (new task()).OnClick;
41 btn.danji();
42 }
43 }
那篇文章写的非常好,我就不介绍了,给出网址,大家可以去看看。
http://www.cnblogs.com/JimmyZhang/archive/2007/09/23/903360.html