using GFramework.Core.Abstractions.Events; using GFramework.Core.Abstractions.Rule; namespace GFramework.Core.Extensions; /// /// 提供对 IContextAware 接口的事件管理扩展方法 /// public static class ContextAwareEventExtensions { /// /// 发送一个事件 /// /// 事件类型 /// 实现 IContextAware 接口的对象 /// 当 contextAware 为 null 时抛出 public static void SendEvent(this IContextAware contextAware) where TEvent : new() { if (contextAware is null) { throw new ArgumentNullException(nameof(contextAware)); } var context = contextAware.GetContext(); context.SendEvent(); } /// /// 发送一个具体的事件实例 /// /// 事件类型 /// 实现 IContextAware 接口的对象 /// 事件实例 /// 当 contextAware 或 e 为 null 时抛出 public static void SendEvent(this IContextAware contextAware, TEvent e) where TEvent : class { if (contextAware is null) { throw new ArgumentNullException(nameof(contextAware)); } if (e is null) { throw new ArgumentNullException(nameof(e)); } var context = contextAware.GetContext(); context.SendEvent(e); } /// /// 注册事件处理器 /// /// 事件类型 /// 实现 IContextAware 接口的对象 /// 事件处理委托 /// 事件注销接口 public static IUnRegister RegisterEvent(this IContextAware contextAware, Action handler) { if (contextAware is null) { throw new ArgumentNullException(nameof(contextAware)); } if (handler is null) { throw new ArgumentNullException(nameof(handler)); } var context = contextAware.GetContext(); return context.RegisterEvent(handler); } /// /// 取消对某类型事件的监听 /// /// 事件类型 /// 实现 IContextAware 接口的对象 /// 之前绑定的事件处理器 public static void UnRegisterEvent(this IContextAware contextAware, Action onEvent) { if (contextAware is null) { throw new ArgumentNullException(nameof(contextAware)); } if (onEvent is null) { throw new ArgumentNullException(nameof(onEvent)); } var context = contextAware.GetContext(); context.UnRegisterEvent(onEvent); } }