【学习笔记】事件如何使用

来源:互联网 发布:淘宝秒刷销量一天千单 编辑:程序博客网 时间:2024/05/01 02:21

经过学习,终于搞清了事件的使用,以下附上一个小例子

事件主要使用三个类:

1. 参数定义类testEventArgs:继承自EventArgs(虽然EventArgs什么也不做)

2. 事件发布类monitor

3. 事件侦听类Receiver

 

using System;using System.Collections.Generic;using System.Text;namespace EventLearn{    class testArgs:EventArgs    {        public string msg;        public testArgs(string msg)        {            this.msg = msg;        }    }    class monitor    {        public delegate void delegateHander(object sender, testArgs e);        public event delegateHander pressKey;         public void Run()        {            do            {                Console.WriteLine("Please press any key. Input 'exit' to finish the process!");                string input=Console.ReadLine();                if (input == "exit")                    break;                pressKey(this,new testArgs(input));            }            while(true);        }    }    class Receiver    {    public Receiver(monitor Monitor)    {        Monitor.pressKey += new monitor.delegateHander(this.process);    }        public void process(object sender, testArgs e)        {            Console.WriteLine("You have input the string: {0}", e.msg);        }    }}


主程序如下:

using System;using System.Collections.Generic;using System.Text;namespace EventLearn{    class Program    {        static void Main(string[] args)        {            monitor Monitor = new monitor();            Receiver receiver = new Receiver(Monitor);            Monitor.Run();            Console.ReadKey();        }    }}


 

原创粉丝点击