生活中的问题,猫叫,把正在偷食的老鼠吓跑了,然后主人被吵醒了
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Test { public partial class Form1 : Form { public Form1() { InitializeComponent(); People people = new People(); Cat cat = new Cat(); people.BoilEvent += Mouse.Move; //注册静态方法 people.BoilEvent += cat.Call; //注册方法 people.BoilEvent += Mouse.Run; //注册方法 people.WakeUp(); //主人醒了,会自动调用注册过对象的方法 } } /// <summary> /// 猫的行为动作 /// </summary> public class Cat { /// <summary> /// 猫叫了 /// </summary> public void Call() { Console.WriteLine("猫发现老鼠,叫了一声!"); } } /// <summary> /// 老鼠的行为动作 /// </summary> public class Mouse { /// <summary> /// 老鼠动了 /// </summary> public static void Move() { Console.WriteLine("老鼠为了找吃的,开始行动!"); } /// <summary> /// 老鼠动了 /// </summary> public static void Run() { Console.WriteLine("老鼠被吓跑了!"); } } /// <summary> /// 人的行为动作 /// </summary> public class People { public delegate void BoilHandler(); //声明委托 public event BoilHandler BoilEvent; //声明事件 /// <summary> /// 人醒了 /// </summary> public void WakeUp() { BoilEvent(); Console.WriteLine("听到猫叫声,主人醒了!"); } } }