EventComponent.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using System;
  2. using System.Collections.Generic;
  3. using Base;
  4. namespace Model
  5. {
  6. /// <summary>
  7. /// 事件分发,可以将事件分发到IL和Mono层,因为是用反射实现的,所以性能较Server用的EventComponent要差
  8. /// </summary>
  9. [EntityEvent(EntityEventId.EventComponent)]
  10. public class EventComponent : Component
  11. {
  12. private Dictionary<int, List<IInstanceMethod>> allEvents;
  13. private void Awake()
  14. {
  15. this.Load();
  16. }
  17. private void Load()
  18. {
  19. this.allEvents = new Dictionary<int, List<IInstanceMethod>>();
  20. Type[] types = DllHelper.GetMonoTypes();
  21. foreach (Type type in types)
  22. {
  23. object[] attrs = type.GetCustomAttributes(typeof(EventAttribute), false);
  24. foreach (object attr in attrs)
  25. {
  26. EventAttribute aEventAttribute = (EventAttribute)attr;
  27. IInstanceMethod method = new MonoInstanceMethod(type, "Run");
  28. if (!this.allEvents.ContainsKey(aEventAttribute.Type))
  29. {
  30. this.allEvents.Add(aEventAttribute.Type, new List<IInstanceMethod>());
  31. }
  32. this.allEvents[aEventAttribute.Type].Add(method);
  33. }
  34. }
  35. types = DllHelper.GetHotfixTypes();
  36. foreach (Type type in types)
  37. {
  38. object[] attrs = type.GetCustomAttributes(typeof(EventAttribute), false);
  39. foreach (object attr in attrs)
  40. {
  41. EventAttribute aEventAttribute = (EventAttribute)attr;
  42. IInstanceMethod method = new ILInstanceMethod(type, "Run");
  43. if (!this.allEvents.ContainsKey(aEventAttribute.Type))
  44. {
  45. this.allEvents.Add(aEventAttribute.Type, new List<IInstanceMethod>());
  46. }
  47. this.allEvents[aEventAttribute.Type].Add(method);
  48. }
  49. }
  50. }
  51. public void Run(int type, params object[] param)
  52. {
  53. List<IInstanceMethod> iEvents = null;
  54. if (!this.allEvents.TryGetValue(type, out iEvents))
  55. {
  56. return;
  57. }
  58. foreach (IInstanceMethod obj in iEvents)
  59. {
  60. try
  61. {
  62. obj.Run(param);
  63. }
  64. catch (Exception err)
  65. {
  66. Log.Error(err.ToString());
  67. }
  68. }
  69. }
  70. }
  71. }