首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > .NET > C# >

C# 事件 示范 源代码

2012-09-20 
C#事件 示例 源代码using Systemusing System.Collections.Genericusing System.Linqusing System.Text

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);
        }
    }

    public class Test
    {
        public static void Main()
        {
            //创建事件源对象
            mm es = new mm();
            //创建侦听对象
            zz el = new zz();

           //订阅事件
            Console.WriteLine("开始订阅事件");
            el.Subscribe(es);

            //引发事件
            Console.WriteLine("输入一个字符,再按Enter键");

            string s = Console.ReadLine();
            es.RaiseEvent(s.ToCharArray()[0]);
            //取消订阅事件
            Console.WriteLine("开始取消订阅事件!");
            el.UnSubscribe(es);
            //引发事件
            Console.WriteLine("输入一个字符,再按Enter键");
            s = Console.ReadLine();
            es.RaiseEvent(s.ToCharArray()[0]);
            Console.ReadKey();
        }
    }

}

热点排行