更简易的事件分发器

事件核心代码:
using System;

namespace EventCore
{
    public class EventDispatcher
    {
        private Action _action;
        public void Register(Action action) => _action += action;
        public void UnRegister(Action action) => _action -= action;
        public void Trigger() => _action?.Invoke();
    }
    public class EventDispatcher<T>
    {
        private Action<T> _action;
        public void Register(Action<T> action) => _action += action;
        public void UnRegister(Action<T> action) => _action -= action;
        public void Trigger(T t) => _action?.Invoke(t);
    }
}

 事件使用例子:

using System;
using EventCore;

namespace EventTestModule // 测试代码
{
    public static class PlayerEventDefine
    {
        public static readonly EventDispatcher JumpEvent = new(); // 玩家跳跃事件
        public static readonly EventDispatcher<int> LvUpEvent = new(); // 玩家升级事件
    }
    public class EventTest : IDisposable
    {
        public EventTest()
        {
            // 注册事件
            PlayerEventDefine.JumpEvent.Register(OnJumpEvent);
            PlayerEventDefine.LvUpEvent.Register(OnLvUpEvent);
            // 事件触发
            PlayerEventDefine.JumpEvent.Trigger();
            PlayerEventDefine.LvUpEvent.Trigger(12);
        }
        private void OnJumpEvent()
        {
            
        }
        private void OnLvUpEvent(int e)
        {
            
        }
        public void Dispose()
        {
            // 注销事件
            PlayerEventDefine.JumpEvent.UnRegister(OnJumpEvent);
            PlayerEventDefine.LvUpEvent.UnRegister(OnLvUpEvent);
        }
    }
}

 

posted @ 2026-05-09 13:27  apssic  阅读(3)  评论(0)    收藏  举报