日期:2010-10-06  浏览次数:20384 次

  要为类构造一个事件,必须用 event 来声明一个 delegate 型的字段,如:

puclic calss Test{
         public delegate EventHandler(object sender, EventArgs e); //声明为delegate 型的事件;
}

  然后要指定一个事件的名称,并写出处理语句:
        public event  EventHandler Load

  在创建类的实例后定义这个 “Load”事件:
        Test m=new Test();
        m.load=new EventHandler(m_Load);
        void m_Load(object sender, EventArgs e)
        {
                MessageBox.Show(" this is a class event");
        }      

  再看看下面的完整的一段代码:

 using System;
 
 class TestClass
 {
     static void Main(string[] args)
      {
         EventClass myEventClass = new EventClass();
         myEventClass.CustomEvent += new EventClass.CustomEventHandler(CustomEvent1); // 关联事件句柄;
         myEventClass.CustomEvent += new EventClass.CustomEventHandler(CustomEvent2);
        myEventClass.InvokeEvent();
        myEventClass.CustomEvent -= new EventClass.CustomEventHandler(CustomEvent2);
        myEventClass.InvokeEvent();
        myEventClass.Load += new EventClass.CustomEventHandler(Load1);
        myEventClass.onLoad();
    }

    private static void CustomEvent1(object sender, EventArgs e)
    {
        Console.WriteLine("Fire Event 1");
    }

    private static void CustomEvent2(object sender, EventArgs e)
    {
        Console.WriteLine("Fire Event 2");
    }
    private static void Load1(object sender, EventArgs e)
    {
        Console.WriteLine("Current background color is {0}. Please input:", System.Console.BackgroundColor.ToString());
    }
}

public class EventClass
{
    public delegate void CustomEventHandler(object sender, EventArgs e);//首先定义一个委托类型的对象CustomEventHandler

    //用delegate数据类型声明事件,要用event关键字,这里定义了两个字件;
    public event CustomEventHandler CustomEvent;
    public event CustomEventHandler Load;
       
    public void InvokeEvent()
    {
        CustomEvent(this, EventArgs.Empty);
    }
    public void onLoad()
    {
        Console.BackgroundColor = ConsoleColor.Red;
        Load(this, EventArgs.Empty);
        string s = Console.ReadLine();
        if (s != "yuping")
        {
            Console.WriteLine("You must type 'yuping' for change it !");
        }
        else
        {
        &