.Net中的事件处理模型

来源:互联网 发布:dnf端口辅助网盘 编辑:程序博客网 时间:2024/05/09 07:39

首先要明确的一点,事件可以看成一个字段,或者一个属性。一个类有一个Event类型的字段,就说明他拥有一个事件,而Event类型需要定义一个委托delegate类型
所以,Net中的事件处理模型可以归纳如下:
1.定义需要的委托类型  
2.在需要定义事件的类EventClass中定义事件属性
3.在需要处理事件的类ProcessEventClass中根据相应的委托类型定义事件处理函数
4.注册事件处理程序,并根据不同的情况激活

示例程序如下:
using System;
using System.Collections.Generic;
using System.Text;
namespace EventExample
{
  class Program
  {
    static void Main(string[] args)
    {
        EventClass eventclass=new EventClass();
        ProcessEventClass processeventclass=new ProcessEventClass();
        //订阅事件
        eventclass.click+=new EventClass.EventHandler(processeventclass.Process);
        Console.WriteLine("触发事件...");
        eventclass.InvokeEvent();
        Console.WriteLine("完毕.");
    }
  }


  class ProcessEventClass          
  {
    //事件处理程序
    public void Process(object o,EventArgs e)
    {
        Console.WriteLine("I have processed the event!");
    }
  }



  class EventClass
  {
    //定义事件使用的委托
    public delegate void EventHandler(object o, EventArgs e);
    //定义事件
    public event EventHandler click;                  

    //此处以函数代码方式激活,实际应用可能不会如此。如在服务器控件中就以控件事件激活之
    public void InvokeEvent()
    {
        if (click!=null)
      {
          click(new object(),new EventArgs());
      }
    }
  }
}

原创粉丝点击