C#委托和事件 示例 using System; using System.Collections.Generic; using System.Text; namespace 委托和事件 { class Program { static void Main(string[] args) { //实例化猫Tom 和老鼠Jerry 和Jack Cat cat = new Cat("Tom"); Mouse mouse1 = new Mouse("Jerry"); Mouse mouse2 = new Mouse("Jack"); //将Mouse 的Run 方法,通过实例化委托Cat.CatShoutEventHandler 登记到Cat 的CatShout 事件当中。其中“+=”表示增加委托实例对象,即"add_CatShout" cat.CatShout += new Cat.CatShoutEventHandler(mouse1.Run); cat.CatShout += new Cat.CatShoutEventHandler(mouse2.Run); cat.Shout(); Console.WriteLine("\r"); Cat1 cat1 = new Cat1("(有参)猫"); Mouse1 mouse3 = new Mouse1("(有参)Jerry"); Mouse1 mouse4 = new Mouse1("(有叁)Jack"); //写法不变 cat1.CatShout += new Cat1.CatShoutEventHandler(mouse3.Run); cat1.CatShout += new Cat1.CatShoutEventHandler(mouse4.Run); cat1.Shout(); Console.Read(); } } //无参数委托事件 class Cat { private string name; public Cat(string name) { this.name = name; } //申明无参数委托 CatShoutEventHandler public delegate void CatShoutEventHandler(); //申明事件CatShout,它的类型是委托CatShoutEventHandler public event CatShoutEventHandler CatShout; public void Shout() { Console.WriteLine("喵,我是{0}.", name); if (CatShout != null) { //由于CatShout 的类型是委托CatShoutEventHandler()(无参数),所以CatShout()也是无参数,无返回值的,有参数的情况见下面的示例 CatShout();//当执行Shou()方法时,若CatShou中有对象登记事件,则执行CatShout()方法 } } } class Mouse { private string name; public Mouse(string name) { this.name = name; } public void Run() { Console.WriteLine("老猫来了,{0}快跑!", name); } } //有参数委托事件 //增加一个新类,继承EventArgs。作用:在事件触发时,传递数据。 public class CatShoutEventArgs : EventArgs //EventArgs:包含事件数据的类的基类 { private string name; public string Name { get { return name; } set { nam...