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     } 

复制代码

 执行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值