EventComponent.cs 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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<AttributeType>: Component<World>, IAssemblyLoader
  9. where AttributeType : AEventAttribute
  10. {
  11. private Dictionary<int, List<IEvent>> events;
  12. public void Load(Assembly assembly)
  13. {
  14. this.events = new Dictionary<int, List<IEvent>>();
  15. var types = assembly.GetTypes();
  16. foreach (var t in types)
  17. {
  18. object[] attrs = t.GetCustomAttributes(typeof (AttributeType), false);
  19. if (attrs.Length == 0)
  20. {
  21. continue;
  22. }
  23. object obj = Activator.CreateInstance(t);
  24. IEvent iEvent = obj as IEvent;
  25. if (iEvent == null)
  26. {
  27. throw new Exception(string.Format("event not inherit IEvent interface: {0}",
  28. obj.GetType().FullName));
  29. }
  30. AEventAttribute iEventAttribute = (AEventAttribute) attrs[0];
  31. if (!this.events.ContainsKey(iEventAttribute.Type))
  32. {
  33. this.events.Add(iEventAttribute.Type, new List<IEvent>());
  34. }
  35. this.events[iEventAttribute.Type].Add(iEvent);
  36. }
  37. }
  38. public void Run(int type, Env env)
  39. {
  40. List<IEvent> iEventDict = null;
  41. if (!this.events.TryGetValue(type, out iEventDict))
  42. {
  43. return;
  44. }
  45. foreach (var iEvent in iEventDict)
  46. {
  47. iEvent.Run(env);
  48. }
  49. }
  50. }
  51. }