Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 

45 lignes
1.1 KiB

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