GFramework/GFramework.Core/Extensions/ContextAwareEventExtensions.cs
gewuyou 9ce1fa630c refactor(core): 收敛 Core 扩展与测试的机械 warning
- 更新 ContextAware、Store 与通用扩展中的参数空校验写法以满足 analyzer 约束

- 简化 coroutine、pause、log 与 async 测试中的等待和断言包装并保持测试语义不变

- 调整测试替身异常类型与 Result 系列断言样例以减少低风险 warning 噪音
2026-04-25 10:38:48 +08:00

96 lines
3.1 KiB
C#

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