using GFramework.Core.Abstractions.events; namespace GFramework.Core.events; /// /// EasyEvents事件管理器类,用于全局事件的注册、获取和管理 /// 提供了类型安全的事件系统,支持泛型事件的自动创建和检索 /// public class EasyEvents { /// /// 全局单例事件管理器实例 /// private static readonly EasyEvents MGlobalEvents = new(); /// /// 存储事件类型与事件实例映射关系的字典 /// private readonly Dictionary _mTypeEvents = new(); /// /// 获取指定类型的全局事件实例 /// /// 事件类型,必须实现IEasyEvent接口 /// 指定类型的事件实例,如果未注册则返回默认值 public static T Get() where T : IEasyEvent { return MGlobalEvents.GetEvent(); } /// /// 注册指定类型的全局事件 /// /// 事件类型,必须实现IEasyEvent接口且具有无参构造函数 public static void Register() where T : IEasyEvent, new() { MGlobalEvents.AddEvent(); } /// /// 添加指定类型的事件到事件字典中 /// /// 事件类型,必须实现IEasyEvent接口且具有无参构造函数 public void AddEvent() where T : IEasyEvent, new() { _mTypeEvents.Add(typeof(T), new T()); } /// /// 获取指定类型的事件实例 /// /// 事件类型,必须实现IEasyEvent接口 /// 指定类型的事件实例,如果不存在则返回默认值 public T GetEvent() where T : IEasyEvent { return _mTypeEvents.TryGetValue(typeof(T), out var e) ? (T)e : default; } /// /// 获取指定类型的事件实例,如果不存在则创建并添加到事件字典中 /// /// 事件类型,必须实现IEasyEvent接口且具有无参构造函数 /// 指定类型的事件实例 public T GetOrAddEvent() where T : IEasyEvent, new() { var eType = typeof(T); // 尝试从字典中获取事件实例 if (_mTypeEvents.TryGetValue(eType, out var e)) return (T)e; // 如果不存在则创建新实例并添加到字典中 var t = new T(); _mTypeEvents.Add(eType, t); return t; } }