打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C#委托探索之猫和老鼠

场景描述

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

实现代码

 之前实现方式:

 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     } 

 执行结果:

 

源代码: 

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

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
委托,事件(猫,鼠,人联动事类)
C#程序设计笔试题
C#经典笔试题
C#.Net的常见面试试题
.net面试题3
英汉对照小故事---老猫
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服