EventTrigger.cs 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Common.Event
  4. {
  5. public class EventTrigger<T> where T : IEventAttribute
  6. {
  7. private readonly Dictionary<int, SortedDictionary<int, IEvent>> events;
  8. public EventTrigger()
  9. {
  10. this.events = new Dictionary<int, SortedDictionary<int, IEvent>>();
  11. Type type = typeof (T);
  12. var types = type.Assembly.GetTypes();
  13. foreach (var t in types)
  14. {
  15. object[] attrs = t.GetCustomAttributes(type, false);
  16. if (attrs.Length == 0)
  17. {
  18. continue;
  19. }
  20. object obj = Activator.CreateInstance(t);
  21. IEvent iEvent = obj as IEvent;
  22. if (iEvent == null)
  23. {
  24. throw new Exception(string.Format("event not inherit IEvent interface: {0}",
  25. obj.GetType().FullName));
  26. }
  27. IEventAttribute iEventAttribute = (T) attrs[0];
  28. if (!this.events.ContainsKey(iEventAttribute.Type))
  29. {
  30. this.events.Add(iEventAttribute.Type, new SortedDictionary<int, IEvent>());
  31. }
  32. this.events[iEventAttribute.Type].Add(iEventAttribute.Order, iEvent);
  33. }
  34. }
  35. public void Trigger(int type, Env env)
  36. {
  37. SortedDictionary<int, IEvent> iEventDict = null;
  38. if (!this.events.TryGetValue(type, out iEventDict))
  39. {
  40. return;
  41. }
  42. foreach (var iEvent in iEventDict)
  43. {
  44. iEvent.Value.Trigger(env);
  45. }
  46. }
  47. }
  48. }