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)
- {
- }
- }