EventDispatcher.cs 882 B

12345678910111213141516171819202122232425262728293031323334353637
  1. using System;
  2. using System.Collections.Generic;
  3. namespace ET
  4. {
  5. public class EventDispatcher<A>
  6. {
  7. private Dictionary<Type, List<Action<A>>> _list = new();
  8. public EventDispatcher() { }
  9. public Action<A> AddListener<T>(Action<A> action)
  10. {
  11. List<Action<A>> acts;
  12. if (_list.TryGetValue(typeof(T), out acts))
  13. {
  14. acts.Add(action);
  15. }
  16. else
  17. {
  18. _list.Add(typeof(T), new List<Action<A>> { action });
  19. }
  20. return action;
  21. }
  22. public void Notfify(A ev)
  23. {
  24. List<Action<A>> acts;
  25. if (_list.TryGetValue(ev.GetType(), out acts))
  26. {
  27. foreach (var act in acts)
  28. {
  29. act.Invoke(ev);
  30. }
  31. }
  32. }
  33. }
  34. }