using System.Collections.Generic; public class MsgHandler { public delegate void DelMsgHandler(ModelData msg); private static Dictionary mDicMsgs = new Dictionary(); /// /// 添加监听者 /// /// /// public static void AddListener(string msgType, DelMsgHandler handler) { //判空 if (mDicMsgs == null) mDicMsgs = new Dictionary(); if (!mDicMsgs.ContainsKey(msgType)) mDicMsgs.Add(msgType, null); //增加监听 mDicMsgs[msgType] += handler; } /// /// 去除对参数handler的监听 /// /// 消息类型 /// 被监听方法 public static void RemoveListener(string msgType, DelMsgHandler handler) { if (mDicMsgs != null && mDicMsgs.ContainsKey(msgType)) mDicMsgs[msgType] -= handler; } /// /// 清除所有的监听者 /// public static void ClearAllListeners() { if (mDicMsgs != null) mDicMsgs.Clear(); } /// /// 分发消息 /// /// 消息类型 /// 分发的内容 public static void SendMsg(string msgType, ModelData msg) { DelMsgHandler handler; if (mDicMsgs != null && mDicMsgs.TryGetValue(msgType, out handler)) { if (handler != null) handler(msg); } } /// /// 群发消息 /// /// 消息内容 public static void AllSendMsg(ModelData msg) { foreach (var item in mDicMsgs) { item.Value(msg); } } } public class Msg { public string Key { get; private set; } public object Value { get; private set; } public Msg(string key, object value) { this.Key = key; this.Value = value; } }