更简易的事件分发器

📅 2026/7/9 7:23:45 👁️ 阅读次数 📝 编程学习
更简易的事件分发器
事件核心代码:
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);}}
}