class Cat { private string _name; public Cat(string name) { _name = name; } public void Shout() { Console.WriteLine("瞄,我是"+_name+",我来了!"); CatShout(); //第三步,触发点,事件要加括号 } public delegate void CatShoutEventHandler(); //第一步,声明委托,要加圆括号 public event CatShoutEventHandler CatShout; //第二步,声明事件,类型为以上委托类型 } class Mouse { public string _name; public Mouse(string name) { _name = name; } public void Run() { Console.WriteLine("猫来了,我是"+_name+",快跑!"); } } static void Main(string[] args) { Cat cat=new Cat("Tom"); Mouse jerry=new Mouse("Jerry"); Mouse jack=new Mouse("Jack"); cat.CatShout += new Cat.CatShoutEventHandler(jerry.Run); //第四步,将相关方法的委托登记到事件 cat.CatShout += new Cat.CatShoutEventHandler(jack.Run); cat.Shout(); Console.ReadLine(); }
时间: 2024-10-13 03:44:26