EventComponent.cs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using System.Threading.Tasks;
  5. using Common.Base;
  6. using Common.Event;
  7. namespace Model
  8. {
  9. public class EventComponent<AttributeType>: Component<World>, IAssemblyLoader
  10. where AttributeType : AEventAttribute
  11. {
  12. private Dictionary<int, List<IEventSync>> eventSyncs;
  13. private Dictionary<int, List<IEventAsync>> eventAsyncs;
  14. public void Load(Assembly assembly)
  15. {
  16. this.eventSyncs = new Dictionary<int, List<IEventSync>>();
  17. this.eventAsyncs = new Dictionary<int, List<IEventAsync>>();
  18. Type[] types = assembly.GetTypes();
  19. foreach (Type t in types)
  20. {
  21. object[] attrs = t.GetCustomAttributes(typeof (AttributeType), false);
  22. if (attrs.Length == 0)
  23. {
  24. continue;
  25. }
  26. object obj = Activator.CreateInstance(t);
  27. IEventSync iEventSync = obj as IEventSync;
  28. if (iEventSync != null)
  29. {
  30. AEventAttribute iEventAttribute = (AEventAttribute)attrs[0];
  31. if (!this.eventSyncs.ContainsKey(iEventAttribute.Type))
  32. {
  33. this.eventSyncs.Add(iEventAttribute.Type, new List<IEventSync>());
  34. }
  35. this.eventSyncs[iEventAttribute.Type].Add(iEventSync);
  36. continue;
  37. }
  38. IEventAsync iEventAsync = obj as IEventAsync;
  39. // ReSharper disable once InvertIf
  40. if (iEventAsync != null)
  41. {
  42. AEventAttribute iEventAttribute = (AEventAttribute)attrs[0];
  43. if (!this.eventAsyncs.ContainsKey(iEventAttribute.Type))
  44. {
  45. this.eventAsyncs.Add(iEventAttribute.Type, new List<IEventAsync>());
  46. }
  47. this.eventAsyncs[iEventAttribute.Type].Add(iEventAsync);
  48. continue;
  49. }
  50. throw new Exception(
  51. string.Format("event not inherit IEventSync or IEventAsync interface: {0}",
  52. obj.GetType().FullName));
  53. }
  54. }
  55. public async Task Run(int type, Env env)
  56. {
  57. List<IEventSync> iEventSyncs = null;
  58. if (this.eventSyncs.TryGetValue(type, out iEventSyncs))
  59. {
  60. foreach (IEventSync iEventSync in iEventSyncs)
  61. {
  62. iEventSync.Run(env);
  63. }
  64. }
  65. List<IEventAsync> iEventAsyncs = null;
  66. // ReSharper disable once InvertIf
  67. if (this.eventAsyncs.TryGetValue(type, out iEventAsyncs))
  68. {
  69. foreach (IEventAsync iEventAsync in iEventAsyncs)
  70. {
  71. await iEventAsync.RunAsync(env);
  72. }
  73. }
  74. throw new Exception(
  75. string.Format("no event handler, AttributeType: {0} type: {1}",
  76. typeof(AttributeType).Name, type));
  77. }
  78. }
  79. }