MsgHandler.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using System.Collections.Generic;
  2. public class MsgHandler
  3. {
  4. public delegate void DelMsgHandler(ModelData msg);
  5. private static Dictionary<string, DelMsgHandler> mDicMsgs = new Dictionary<string, DelMsgHandler>();
  6. /// <summary>
  7. /// 添加监听者
  8. /// </summary>
  9. /// <param name="msgType"></param>
  10. /// <param name="handler"></param>
  11. public static void AddListener(string msgType, DelMsgHandler handler)
  12. {
  13. //判空
  14. if (mDicMsgs == null) mDicMsgs = new Dictionary<string, DelMsgHandler>();
  15. if (!mDicMsgs.ContainsKey(msgType)) mDicMsgs.Add(msgType, null);
  16. //增加监听
  17. mDicMsgs[msgType] += handler;
  18. }
  19. /// <summary>
  20. /// 去除对参数handler的监听
  21. /// </summary>
  22. /// <param name="msgType">消息类型</param>
  23. /// <param name="handler">被监听方法</param>
  24. public static void RemoveListener(string msgType, DelMsgHandler handler)
  25. {
  26. if (mDicMsgs != null && mDicMsgs.ContainsKey(msgType)) mDicMsgs[msgType] -= handler;
  27. }
  28. /// <summary>
  29. /// 清除所有的监听者
  30. /// </summary>
  31. public static void ClearAllListeners()
  32. {
  33. if (mDicMsgs != null) mDicMsgs.Clear();
  34. }
  35. /// <summary>
  36. /// 分发消息
  37. /// </summary>
  38. /// <param name="msgType">消息类型</param>
  39. /// <param name="msg">分发的内容</param>
  40. public static void SendMsg(string msgType, ModelData msg)
  41. {
  42. DelMsgHandler handler;
  43. if (mDicMsgs != null && mDicMsgs.TryGetValue(msgType, out handler))
  44. {
  45. if (handler != null)
  46. handler(msg);
  47. }
  48. }
  49. /// <summary>
  50. /// 群发消息
  51. /// </summary>
  52. /// <param name="msg">消息内容</param>
  53. public static void AllSendMsg(ModelData msg)
  54. {
  55. foreach (var item in mDicMsgs)
  56. {
  57. item.Value(msg);
  58. }
  59. }
  60. }
  61. public class Msg
  62. {
  63. public string Key { get; private set; }
  64. public object Value { get; private set; }
  65. public Msg(string key, object value)
  66. {
  67. this.Key = key;
  68. this.Value = value;
  69. }
  70. }