class Program { static void Main(string[] args) { //委托 Events ev = new Events(); ev.Mains(); ev.drart = new Deart(Cat.Miao); ev.drart += Mouse.Mou; ev.drart += People.Peo; //事件,1不能被初始化,2不能被外部调用 ev.EvenDeart += Cat.Miao; ev.EvenDeart += Mouse.Mou; ev.EvenDeart += People.Peo; ev.Mains(); Console.ReadLine(); } }
public delegate void Deart(); public class Events { public Deart drart;//声明一个委托 //事件的本质就是一个委托的实例 public event Deart EvenDeart;//委托是一个类型,事件是委托的类型的实例 public void Mains() { Console.WriteLine("开始"); Console.WriteLine("******委托********"); if (drart != null) drart.Invoke(); Console.WriteLine("******事件********"); if (EvenDeart != null) EvenDeart.Invoke(); } }
public class Cat { public static void Miao() { Console.WriteLine("瞄叫了一声"); } } public class Mouse { public static void Mou() { Console.WriteLine("老鼠逃跑"); } } public class People { public static void Peo() { Console.WriteLine("人被吵醒"); } }