C#中的事件介绍

2019-12-26 11:13:48丽君

 

自定义事件的实例

 

从网上找了一个比较容易理解的自定义事件实例,记录再次方便学习。原文地址:http://www.easck.com/kaifa/cjc/46234.html

发布事件的类TestEventSource:

复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

 

namespace EventDemo
{
    /// <summary>
    /// 发布事件的类
    /// </summary>
    public class TestEventSource
    {
        //定义事件参数类
        public class TestEventArgs : EventArgs
        {
            public readonly char KeyToRaiseEvent;
            public TestEventArgs(char keyToRaiseEvent)
            {
                KeyToRaiseEvent = keyToRaiseEvent;
            }
        }
        //定义delegate
        public delegate void TestEventHandler(object sender, TestEventArgs e);
        //用event 关键字声明事件对象
        public event TestEventHandler TestEvent;
        //事件触发方法
        protected virtual void OnTestEvent(TestEventArgs e)
        {
            if (TestEvent != null)