您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 

48 行
1.5 KiB

  1. using System;
  2. using System.Collections.Generic;
  3. namespace SUISS.Core
  4. {
  5. public class Messenger
  6. {
  7. public void Subscribe<T>(Action<T> callback) where T : class
  8. {
  9. Action<object> action = delegate (object o)
  10. {
  11. callback((T)((object)o));
  12. };
  13. if (this.events.ContainsKey(typeof(T)))
  14. {
  15. this.events[typeof(T)] = (Action<object>)Delegate.Combine(this.events[typeof(T)], action);
  16. }
  17. else
  18. {
  19. this.events.Add(typeof(T), action);
  20. }
  21. this.lookupTable.Add(callback, action);
  22. }
  23. public void Unsubscribe<T>(Action<T> callback) where T : class
  24. {
  25. if (this.events.ContainsKey(typeof(T)) && this.lookupTable.ContainsKey(callback))
  26. {
  27. (this.events)[typeof(T)] = (Action<object>)Delegate.Remove(this.events[typeof(T)], this.lookupTable[callback]);
  28. this.lookupTable.Remove(callback);
  29. }
  30. }
  31. public void Invoke<T>(T evt) where T : class
  32. {
  33. Action<object> action;
  34. if (this.events.TryGetValue(typeof(T), out action) && action != null)
  35. {
  36. action(evt);
  37. }
  38. }
  39. private Dictionary<Type, Action<object>> events = new Dictionary<Type, Action<object>>();
  40. private Dictionary<object, Action<object>> lookupTable = new Dictionary<object, Action<object>>();
  41. }
  42. }