c#委托

用一个简单的例子了解c#委托

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

//about how to use delegate and event.
namespace DelegetTestSpace {
    public class TestEventSource {

        //定义事件参数类
        public class TestEventArgs :EventArgs{
            public readonly char KeyToRaiseEvent;
            public TestEventArgs(char keyToRaiseEvent) {
                KeyToRaiseEvent = keyToRaiseEvent;
            }
        }
        //定义委托
        public delegate void TestEventHander(object sender, TestEventArgs e);
        /// <summary>
        /// 用event关键字申明事件对象
        /// </summary>
        public event TestEventHander TestEvent;
        //用on申明事件触发方法
        public void OnTestEvent(object sender, TestEventArgs e) {
            if (TestEvent != null) {
                TestEvent(this, e);
            }
        }
        //引发事件
        public void RaiseEvent(char keyToRaiseEvent) {
            TestEventArgs e = new TestEventArgs(keyToRaiseEvent);
            OnTestEvent(null, e);
        }
    }

    /// <0summary>
    /// 监听事件的类
    /// </summary>

    public class TestEventListener {
        //定义处理事件的方法,与申明事件的委托具有相同的参数和返回值。
        public void KeyPressed(object sender, TestEventSource.TestEventArgs e) {
            Console.WriteLine("发送者 :{0},所按键为{1}", sender,e.KeyToRaiseEvent);
        }
        //订阅事件,即想一个事件添加函数
        public void Subscribe(TestEventSource eventSource) {
            eventSource.TestEvent += KeyPressed;
        }
        //取消订阅
        public void UnSubscribe(TestEventSource eventSource){
            eventSource.TestEvent -= KeyPressed;
        }
    }

    class Program {
        static void Main(string[] args) {
            TestEventSource eventSource = new TestEventSource();
            TestEventListener eventListen = new TestEventListener();
            Console.WriteLine("订阅事件");
            eventListen.Subscribe(eventSource);
            Console.WriteLine("输入一个字符,并按回车键");
            string s = Console.ReadLine();
            eventSource.RaiseEvent(s.ToCharArray()[0]);
            Console.WriteLine("取消订阅");
            eventListen.UnSubscribe(eventSource);
            Console.WriteLine("输入一个字符,并按回车键");
             s = Console.ReadLine();
             eventSource.RaiseEvent(s.ToCharArray()[0]);
            Console.ReadLine();

        }
    }
}


转载请表标明出处。

posted @ 2015-08-12 10:18  小精灵儿Pawn  Views(159)  Comments(0Edit  收藏  举报

如果您觉得此文有帮助,可以打赏点钱给我支付宝。 谢谢 -):