关于Event与delegate的一些对比

王朝other·作者佚名  2006-01-09
窄屏简体版  字體: |||超大  

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");

}

}

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
 
© 2005- 王朝網路 版權所有  導航