EventComponent.cs 1.7 KB

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