EventTrigger.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. using System;
  2. using System.Collections.Generic;
  3. namespace Common.Component
  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}", obj.GetType().FullName));
  25. }
  26. IEventAttribute iEventAttribute = (T) attrs[0];
  27. if (!this.events.ContainsKey(iEventAttribute.Type))
  28. {
  29. this.events.Add(iEventAttribute.Type, new SortedDictionary<int, IEvent>());
  30. }
  31. this.events[iEventAttribute.Type].Add(iEventAttribute.Order, iEvent);
  32. }
  33. }
  34. public void Trigger(int type, Env env)
  35. {
  36. SortedDictionary<int, IEvent> iEventDict = null;
  37. if (!this.events.TryGetValue(type, out iEventDict))
  38. {
  39. return;
  40. }
  41. foreach (var iEvent in iEventDict)
  42. {
  43. iEvent.Value.Trigger(env);
  44. }
  45. }
  46. }
  47. }