C# 自定义事件

C#自定义事件和java有所不同,涉及到委托。下面代码包括自定义事件从事件定义到事件触发和执行的全过程。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
//using System.Timers;

namespace EventTest
{
    //定义一个委托MessageHandler,可以看作是一个类。
    public delegate void MessageHandler(string messageText);
    class Connections
    {

	
	//定义一个事件MessageArrive,是委托的实例
        public event MessageHandler MessageArrive;
        private Timer pollTimer;
        private static Random random = new Random();

        public Connections()
        {
            this.pollTimer = new Timer();
            pollTimer.Elapsed += new ElapsedEventHandler(Display);
        }

        public void Connect()
        {
            pollTimer.Start();
        }

        public void Disconnect()
        {
            pollTimer.Stop();
        }

        public void Display(object source, ElapsedEventArgs e)
        {
            Console.WriteLine("New Message Coming");
            if (random.Next(9) == 0 && MessageArrive != null)
            {
		//触发MessageArrive事件
                MessageArrive("New Message Arrived, And has been handled successfully");
            }
        }
        static void Main(string[] args)
        {
            Connections connector = new Connections();
            Display displayor = new Display();
	    //将一个委托实例赋值给事件MessageArrive,参数为方法DisplayMessage,方法的参数要与委托类的参数一致。
            connector.MessageArrive += new MessageHandler(displayor.DisplayMessage);
            connector.Connect();
            Console.ReadKey();
        }
    }


    public class Display
    {
        public void DisplayMessage(string text)
        {
            Console.WriteLine(text);
        }
    }
}



 

 

posted @ 2013-07-10 10:50  爱生活,爱编程  阅读(304)  评论(0编辑  收藏  举报