using System; namespace ConsoleApplication3 { public delegate void MyDelegate(string str); class Class1 { private static void Hello(string str){ Console.WriteLine("Hello "+str); } private static void GoodBye(string str){ Console.WriteLine("GoodBye "+str); } static void Main(string[] args) { MyDelegate a,b,c,d; a = new MyDelegate(Hello); b = new MyDelegate(GoodBye); c = a + b; d = c - a; a("A"); b("B"); c("C"); d("D"); Console.ReadLine(); } } }
我的理解就是,delegate就是一个函数的指针,用他声明的变量实质上就是一个函数,这就要求绑定的时候函数的返回值和参数列表必须符合delegate声明时候的要求。 这时候,我来比较一下event this.Load += new System.EventHandler(this.Page_Load); 很显然,这里的this.Load是一个事件,也是一个delegate,而这里的System.EventHandler()也是一个delegate,而且,他的返回值与参数列表和this.Load是相同的。这时候绑定的Page_Load,是System.EventHandler绑定的一个具体的函数,跟前两者的返回值和参数列表都相同。当this.Load事件发生的时候,触发了新new的System.EventHandler,从而运行了Page_Load. 找到了一个例子,事件处理的 using System; public class EventTest { public delegate void MyEventHandler(object sender,System.EventArgs e); public static void MyEventFunc(object sender,System.EventArgs e) { Console.WriteLine("My Event is done!"); } private event MyEventHandler myevent; public EventTest() {
this.myevent+=new MyEventHandler(MyEventFunc); } public void RaiseEvent() { EventArgs e=new EventArgs(); if(myevent!=null) myevent(this,e); }
public static void Main() { EventTest et=new EventTest(); Console.WriteLine("Please input a"); if(Console.ReadLine()=="a") et.RaiseEvent(); else Console.WriteLine("Error"); } }

|