Blink

纸上得来终觉浅,绝知此事要躬行

C#:基于类型的简易事件监听与广播系统

作用

在枚举事件系统中,我们的每一个事件都是通过一个枚举进行标识的,但是在基于类的事件系统中,我们使用类进行事件的标识,每一个事件对应一个类,这样相比于枚举的方式,我们可以通过事件类传递若干个参数,没有参数的限制

代码

  • 事件定义
/// <summary>
/// 事件接口
/// </summary>
public interface IEvent
{

}

/// <summary>
/// 具体的事件,这里为购买事件
/// 类中可以定义这个事件需要用的数据
/// </summary>
public class BuyEvent : IEvent
{
    // 商品名称
    public string GoodsName { get; set; }
    // 商品价格
    public int Price { get; set; }
}
  • 事件的管理类
using System;
using System.Collections.Generic;

public class EventSystem
{
    // 用来存储事件监听的字典
    private static Dictionary<Type, Delegate> m_EventDic = new Dictionary<Type, Delegate>();

    /// <summary>
    /// 注册事件监听
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="callback"></param>
    public static void Register<T>(Action<T> callback) where T : IEvent
    {
        Type type = typeof(T);
        if (!m_EventDic.ContainsKey(type))
        {
            m_EventDic.Add(type, null);
        }
        m_EventDic[type] = m_EventDic[type] as Action<T> + callback;
    }

    /// <summary>
    /// 取消注册
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="callback"></param>
    public static void Unregister<T>(Action<T> callback)
    {
        Type type = typeof(T);
        if (m_EventDic.ContainsKey(type))
        {
            m_EventDic[type] = (m_EventDic[type] as Action<T>) - callback;
            if (m_EventDic[type] == null)
            {
                m_EventDic.Remove(type);
            }
        }
    }

    /// <summary>
    /// 广播消息
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="data"></param>
    public static void Broadcast<T>(T data) where T : IEvent
    {
        Type type = typeof(T);
        Delegate callback = null;
        if (m_EventDic.TryGetValue(type, out callback) && callback != null)
        {
            (m_EventDic[type] as Action<T>)(data);
        }
    }
}
  • 测试
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Test : MonoBehaviour
{
    private void Start()
    {
        // 注册监听
        EventSystem.Register<BuyEvent>(Callback);
    }

    private void Update()
    {
        // 按下Q键广播事件消息
        if (Input.GetKeyDown(KeyCode.Q))
        {
            EventSystem.Broadcast<BuyEvent>(new BuyEvent
            {
                GoodsName = "MacBook",
                Price = 12999
            });
        }

        // 按下A键注销监听
        if (Input.GetKeyDown(KeyCode.A))
        {
            EventSystem.Unregister<BuyEvent>(Callback);
        }
    }

    // 事件监听的回调函数
    private void Callback(BuyEvent obj)
    {
        Debug.Log(obj.GoodsName + " -> " + obj.Price);
    }
}

《C#:基于类型的简易事件监听与广播系统》

点赞

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注