事件与委托

今天看了一个面试题:猫大叫一声,所有的老鼠都开始逃跑,主人被惊醒。(C#语言)

晚上坐在电脑面前,想复习复习事件和委托,这个题目正好拿来练手。

首先写一个猫的类:

Code

然后我们再写一个参数类,为的是把事件发生者的名字传过来,也就是把猫的名字传过来。

 

 1public class CatCryEventArgs:EventArgs
 2{
 3    private string name;
 4    public string Name
 5    {
 6       get
 7       {
 8          return name;
 9       }

10       set
11       {
12          name = value;
13       }

14    }

15    public CatCryEventArgs(string name)
16    {
17        this.name = name;
18    }

19}

然后再写一个委托:

1 public delegate void CatCryHander(object sender,CatCryEventArgs e);

接着在第一个Cat类中写入事件:

1 public event CatCryHander cryHander;

接着来写老鼠的类了,定义类名为Mouse:

Code

再来写主人的类,类名定义为Master:

Code

回过头来看,发现少了个方法:在Cat类中要加上猫叫的方法:

1 public void CatCry()
2 {
3    CatCryEventArgs e = new CatCryEventArgs(this.name);
4    console.WriteLine(name+"叫了一声!");
5    if(cryHander!=null)
6    {
7        cryHander(this,e);
8    }
9 }

到此,所有有关的类全部写完,现在就写主函数:

1 public static void Main(string[] args)
2 {
3     Cat cat = new Cat("加菲猫");
4     Mouse bigmouse = new Mouse("大老鼠",cat);
5     Mouse smallmouse = new Mouse("小老鼠",cat);
6     Master master = new Master("GoldKevin",cat);
7     cat.CatCry();
8 }

 

 

 

posted @ 2009-03-25 00:24  goldkevin  阅读(254)  评论(1编辑  收藏  举报