1.先定义事件参数类: EventArgs 是基类,不建议直接使用,因为通用的东西针对性不强,容易混乱(特别是找bug 的时候)... MyEvent 的具体的派生类,建议的使用方法就是每个种类的事件派生一个类,比如UIEvent,ServerEvent神马的,根据具体作用来命名.
- /// <summary>
- /// 事件参数基类
- /// </summary>
- public class EventArgs
- {
- public object Parameter;
- }
- /// <summary>
- /// 自定义事件参数
- /// </summary>
- public class MyEvent : EventArgs
- {
- public int ID;
- public string Name; // ...etc
- }
- /// <summary>
- /// 事件管理类
- /// </summary>
- public class EventManager
- {
- //单例模式.
- public static readonly EventManager Instance = new EventManager();
- private EventManager() { }
- //事件委托.
- public delegate void EventDelegate<T>(T e) where T : EventArgs;
- //保存所有事件<span style="font-family:Arial,Helvetica,sans-serif">接收方法</span>.
- readonly Dictionary<Type, Delegate> _delegates = new Dictionary<Type, Delegate>();
- //添加一个事件接收方法.
- public void AddListener<T>(EventDelegate<T> listener) where T : EventArgs
- {
- Delegate d;
- if (_delegates.TryGetValue(typeof(T), out d))
- {
- _delegates[typeof(T)] = Delegate.Combine(d, listener);
- }
- else
- {
- _delegates[typeof(T)] = listener;
- }
- }
- //删除一个事件接受方法
- public void RemoveListener<T>(EventDelegate<T> listener) where T : EventArgs
- {
- Delegate d;
- if (_delegates.TryGetValue(typeof(T), out d))
- {
- Delegate currentDel = Delegate.Remove(d, listener);
- if (currentDel == null)
- {
- _delegates.Remove(typeof(T));
- }
- else
- {
- _delegates[typeof(T)] = currentDel;
- }
- }
- }
- //发送事件.
- public void Send<T>(T e) where T : EventArgs
- {
- if (e == null)
- {
- throw new ArgumentNullException("e");
- }
- Delegate d;
- if (_delegates.TryGetValue(typeof(T), out d))
- {
- EventDelegate<T> callback = d as EventDelegate<T>;
- if (callback != null)
- {
- callback(e);
- }
- }
- }
- }
3. 使用示例: 使用灰常简单,如下: 先添加一个事件接收方法(就是当事件被发出的时候会调用的接收方法), 然后需要触发事件时使用Send方法发送即可.
- /// <summary>
- /// 使用示例
- /// </summary>
- public class Test
- {
- public Test()
- {
- //添加事件接收方法
- EventManager.Instance.AddListener<MyEvent>(ReceiveEvent);
- //发送MyEvent事件, 之后ReceiveEvent(MyEvent e)方法将被调用.
- MyEvent e = new MyEvent(); //事件参数.
- e.ID =0;
- e.Name = "XOXOOX";
- //事件发送
- EventManager.Instance.Send<MyEvent>(e);
- }
- //接收MyEvent事件的方法.
- public void ReceiveEvent(MyEvent e)
- {
- }
- }