消息与事件

发表于:2007-06-30来源:作者:点击数: 标签:
namespace ControlDelegate { /// summary /// 事件发送者,可以触发事件 /// /summary public delegate void EventSenderEventHandler(string strText); public class EventSender:System.EventArgs { public EventSender() { //相当于一个安纽类,这在WINFOR
namespace ControlDelegate
{
    /// <summary>
    /// 事件发送者,可以触发事件
    /// </summary>
    public delegate void EventSenderEventHandler(string strText);

    public class EventSender:System.EventArgs
    {
        public EventSender()
        {
            //相当于一个安纽类,这在WINFORM中
            //类的具体是不用我们实现的了,我们只管继承就可以了
        }

        public event EventSenderEventHandler TextOut;
        

        public void OnTextOut()
        {
            if(null!=TextOut)
            {
                TextOut("事件点火了");
                return;
            }
            Console.WriteLine("事件没被预定");
        }        
    }
   
   /// <summary>
    /// 事件的接收者,捕捉事件,并做出响应
    /// </summary>
    public class EventReceiver
    {
        public EventReceiver()
        {
            //我们通常编的WINFORM程序好象都是做为消息接收者程序
            //而消息发送者该是WINDOWS本身吧
        }

        public static void Main()
        {
            EventSender sender=new EventSender();//相当于一个安纽类
            sender.TextOut+=new EventSenderEventHandler(EventReceiver.StaticCatchEvent);
            sender.OnTextOut();
            

            sender.TextOut-=new EventSenderEventHandler(EventReceiver.StaticCatchEvent);
            sender.OnTextOut();

            EventReceiver receiver=new EventReceiver();
            sender.TextOut+=new EventSenderEventHandler(receiver.InstanceCatchEvent);
            sender.OnTextOut();//相当于我们点击某个按纽吧

            Console.ReadLine();

        }

        public static void StaticCatchEvent(string strText)
        {
            Console.WriteLine(strText);
        }

        public void InstanceCatchEvent(string strText)
        {
            Console.WriteLine("实例的"+strText);
        }
        
    }
}

执行顺序:
  main()
  建立了发送者和接受者之间的关系
  接受者响应发送者的TextOut事件,并用自己的
           StaticCatchEvent()
         和
           InstanceCatchvent()
  去处理发送者的TextOut事件
  
  当我们调用onTextOut去激活发送者事件时
  消息发送者会寻找谁对我的这个事件感兴趣
  找到了是消息接受者EventReceiver的一个方法
  ok! 这个方法就被调用了
  (注意呀,
    这个方法的模式和消息发送者的事件的模式是一样的了)
  哈哈

我也是自己说的这些
  一定有不妥的地方
  希望指正
  
  

原文转自:http://www.ltesting.net