委托和事件相同的功能
class Dem5 { public Action deHandler; public event Action eveHa; public Dem5() { deHandler += Method1; deHandler += Method2; eveHa += Method1; eveHa += Method2; } public void Method1() { Console.WriteLine("谁又能怎样"); } public void Method2() { Console.WriteLine("那有怎样"); } public void Test1() { deHandler.Invoke(); eveHa.Invoke(); } static void Main(string[] args) { Dem5 obj = new Dem5(); obj.Test1(); } }
区别1:委托可以声明一个局部变量,而事件不可以
区别2:委托可以作为方法的参数,事件不可以
事件可以看做是委托的特殊化对象。