分享

C#委托探索之猫和老鼠

 昵称10504424 2012-09-12

场景描述

猫和老鼠:猫来了,老鼠跑掉!怎么实现?

实现代码

 之前实现方式:

复制代码
 1     public class Cat
 2     {
 3         
 4         public void ScreamOut(string msg)
 5         {
 6              mouse.RunAway();
 7         }
 8     }
 9     public class Mouse
10     {
11         
12         public void RunAway()
13          
14 
15     }
复制代码

 

 但是如果老鼠繁殖多了,很多老鼠同时都要跑掉,有的向南有的向北,怎么办呢?重写猫的ScreamOut 方法,这样显然不好;

 现实中的情况是,每个老鼠听到猫来了这个情况,自己有自己的逃跑方式,于是委托用到了这里,即:委托相当于一个方法 但是它的参数也是一个方法,这就不能用一般的方法那样定义了;

 委托实现如下: 

 猫类:

复制代码
 1 public class Cat

 

 2     {
 3         public string Name { getset; }
 4         public delegate void ScreamEventHandler(object sender, ScreamEventArgs e);
 5         public event ScreamEventHandler Scream;
 6         public virtual void OnScream(ScreamEventArgs e)
 7         {
 8             if (this.Scream != null)
 9             {
10                 this.Scream(this, e);
11             }
12         }
13         public void ScreamOut(string msg)
14         {
15             ScreamEventArgs e = new ScreamEventArgs(msg);
16             OnScream(e);
17         }
18     }
复制代码

 鼠类:

复制代码
 1 public class Mouse

 

 2     {
 3         public string Name { getset; }
 4         public Mouse(Cat cat)
 5         {
 6             cat.Scream += new Cat.ScreamEventHandler(cat_Scream);
 7             cat.Scream += this.RunAway;
 8         }
 9         public void RunAway(object sender, ScreamEventArgs e)
10         {
11             Cat c = (Cat)sender;
12             Console.WriteLine("{0} coming,she said:\"{1}\",{2} running!(Running...)", c.Name, e.Msg, this.Name);
13         }
14         void cat_Scream(object sender, ScreamEventArgs e)
15         {
16             Cat c = (Cat)sender;
17             Console.WriteLine("{0} coming,she said:\"{1}\",{2} running!", c.Name, e.Msg, this.Name);
18         }
19 
20     }
复制代码

 这里的委托定义和.net Framework 类库定义方式相同,有助于了解系统提供的委托机制,所以还有一个猫叫事件的参数类:

复制代码
1 public class ScreamEventArgs
2     {
3         public readonly string Msg;
4         public ScreamEventArgs(string msg)
5         {
6             this.Msg = msg;
7         }

8     } 

复制代码

 主类调用代码:

复制代码
 1 class Program
 2     {
 3         static void Main(string[] args)
 4         {
 5             Cat c1 = new Cat();
 6             c1.Name = "tom";
 7 
 8             Mouse m1 = new Mouse(c1);
 9             m1.Name = "Jearry";
10 
11             Mouse m2 = new Mouse(c1);
12             m2.Name = "Jearry's son";
13 
14             c1.Scream += m2.RunAway;
15 
16             c1.ScreamOut("stop");
17 
18             Console.Read();
19         }

20     } 

复制代码

 执行结果:

 

源代码: 

委托探索之猫和老鼠源代码 

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多