第一种解决方案用事件来解决:是多级的联动:即:猫叫-》老鼠跑-》人醒

 1 public class Cat
 2 {
 3     public delegate void Crying(object sender,EventArgs e);//定义一个猫叫委托
 4     public event Crying cry;//定义猫叫事件
 5     public void OnCry(EventArgs e)
 6     {
 7        if(cry!=null 8        {
 9            cry(this,e);
10        }
11     }
12    public void StartCrying()//猫叫、触发cry事件
13    {
14       MessageBox.Show("猫开始叫了......");
15       EventArgs e=new EventArgs();
16       OnCry(e);
17    }
18 }
19  
20 public class Mouse
21 {
22    public delegate void Runing(Object sender,EventArgs e);
23    public evnet Running run;
24    public void OnRun(EventArgs e)
25    {
26         if(run!=null)
27           {
28              run(this,e); 
29           }
30    }
31    public Mouse(Cat c)
32    {
33        c.cry+=new Cat.Crying(c_Cry);//注册了猫叫事件,老鼠听到猫叫则开始逃跑
34    }
35    void c_Cry(object sender,EvnetArgs e)//老鼠在逃跑时又触发了人被惊醒事件
36    {
37        MessageBox.Show("老鼠开始逃跑了........");
38        EventArgs e=new EventArgs();
39        OnRun(e);
40    }
41 }
42 public class Person
43 {
44      public Person(Mouse m)
45      {
46          m.run+=new Mouse.Runing(m_run);//人注册了老鼠逃跑事件,老鼠逃跑时人被 惊醒
47      }
48      void m_run(object sender,EventArgs e)
49          {
50          MessageBox.Show("人醒了");
51          }
52 }
53 
54 BtnTest_Click(object sender, EventArgs e)
55 {
56     Cat c=new Cat();
57     Mouse m=new Mouse(c);
58     Person p=new Person(m);
59     c.StartCrying();
60 }
View Code

相关文章:

  • 2022-02-03
  • 2022-01-24
  • 2021-10-01
  • 2022-02-14
  • 2021-06-23
  • 2021-07-20
  • 2022-02-02
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-07-30
  • 2022-01-18
  • 2022-12-23
  • 2021-06-26
相关资源
相似解决方案