日期:2014-05-17  浏览次数:20767 次

C# 事件 示例 源代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleAppEventPro
{
    //0.事件触发类
    public class mm
    {
        //1.定义事件参数类
        public class nn : EventArgs
        {
            public readonly char aa;
            public nn(char Inputaa)
            {
                aa = Inputaa;
            }
        }
            //2.定义委托delegate
            public delegate void weituo(Object sender,nn e);

            //3.用Event关键字声明事件对象
            public event weituo TestEvent;

            //4.事件触发方法
            protected virtual void OnTestEvent(nn e)
            {
                if (TestEvent != null)
                {
                    TestEvent(this, e);
                }
            }
            //5.引发方法
            public void RaiseEvent(char aa)
            {
                nn e = new nn(aa);
                OnTestEvent(e);
            }
    }

    //侦听事件的类
    public class zz
    {
        //1.定义处理事件的方法,他与声明事件的delegate具有相同的参数和返回值类型——》事件处理方法
        public void KeyPressed(object sender,mm.nn e)
        {
            Console.WriteLine("发送者为:{0},所按的键为:{1}",sender,e.aa);
        }

        //2.订阅事件
        public void Subscribe(mm eventSource)
        {
            eventSource.TestEvent += new mm.weituo(KeyPressed);
        }

        //3.取消订阅
        public void UnSubscribe(mm eventSource)
        {
            eventSource.TestEvent -= new mm.weituo(KeyPressed);
  &