c# 事件 发布订阅


public class MessageEx
{
    /// <summary>
    /// 定义数据暂存
    /// </summary>
    private static readonly Dictionary<string, List<Action<object>>> _handlers = new();

    /// <summary>
    /// 订阅事件
    /// </summary>
    /// <typeparam name="TEvent"></typeparam>
    /// <param name="handler"></param>
    public static void Subscribe(string key, Action<object> data)
    {
        if (!_handlers.ContainsKey(key))
        {
            _handlers.Add(key, new List<Action<object>>());
        }
        _handlers[key].Add(data);
    }

    // 取消订阅事件  
    /// <summary>
    /// 取消订阅事件 
    /// </summary>
    /// <typeparam name="TEvent"></typeparam>
    /// <param name="handler"></param>
    public static void Unsubscribe(string key, Action<object> handler)
    {
        if (!_handlers.ContainsKey(key))
        {
            return;
        }
        _handlers[key].Remove(handler);
    }


    /// <summary>
    /// 发布事件 
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="eventToPublish"></param>
    public static void Publish(string key, object data)
    {
        if (!_handlers.ContainsKey(key))
        {
            return;
        }

        // 使用 ToList 以避免在迭代时修改集合  
        foreach (var handler in _handlers[key].ToList())
        {
            handler(data);
        }
    }
}
posted @ 2024-11-05 13:59  Hey,Coder!  阅读(3)  评论(0编辑  收藏  举报