c#中事件机制学习

原文地址:http://www.cnblogs.com/zhaotiantang/archive/2009/05/25/1489006.html

c#中事件从本质上说,应该是一个限制了的委托,下面的示例代码应该可以很好的说明这一点:

      这样做的好处是可以随时改变事件发生时的响应函数而不必修改事件类的任何代码,事件发生时执行的函数在运行时才进行绑定。

    class Program
    {
        static void Main(string[] args)
        {
            AlertEq ae = new AlertEq();
            //事件响应函数绑定
            ae.Action += new AlertEq.ActionEventHandler(EventHander.process);
            //发生事件
            ae.action("sichuan", 6);
            ae.action("sichuan", 5);
            ae.action("sichuan", 3);
        }

    }
    //地震事件类,action是发生事件的函数
    class AlertEq
    {

        //定义委托
        public delegate void ActionEventHandler(object o, EarthquackArgs e);

        //申明事件
        public event ActionEventHandler Action;

        //事件发生
        public void action(string area, int rank)
        {
            EarthquackArgs arg = new EarthquackArgs(area, rank);
            Action(this, arg);
        }
    }
    //地震事件的捕获类,负责真正事件的处理
    static class EventHander
    {
        public static void process(object sender, EarthquackArgs message)
        {
            Console.WriteLine(sender.ToString() + " make the alert;");
            Console.WriteLine("we have a " + message.rank + " rank earthquack " + " in " + message.area + " province!");
        }

    }

    //事件参数类
    public class EarthquackArgs : EventArgs
    {
        public string area;
        public int rank;
        public EarthquackArgs(string area, int rank)
            : base()
        {
            this.area = area;
            this.rank = rank;
        }
    }

原文地址:https://www.cnblogs.com/yibinboy/p/1633074.html