关于事件与委托的一些对比

来源:互联网 发布:苹果6怎样分亨网络 编辑:程序博客网 时间:2024/05/04 19:37
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");
}
}

//在这里myEvent是一个事件,也是一个delegate,给他加了一个处理的的delegate,也就是一个eventHandler,就是给这个事件添加的处理函数。在构造函数里面,把MyEventFunc和handler进行绑定。那么,如果触发了事件,就执行绑定的函数MyEventFunc.

Ivony... 发表于 2005-03-03 10:47 AM    
event就是delegate,只不过是delegate的缩减功能版,或者说受限版。。。。event去掉了delegate的直接赋值功能,其他与delegate一样。 

也就是说event就是一个不能使用=运算符的delegate。