EventComponent.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. #if ILRuntime
  36. types = DllHelper.GetHotfixTypes();
  37. foreach (Type type in types)
  38. {
  39. object[] attrs = type.GetCustomAttributes(typeof(EventAttribute), false);
  40. foreach (object attr in attrs)
  41. {
  42. EventAttribute aEventAttribute = (EventAttribute)attr;
  43. IInstanceMethod method = new ILInstanceMethod(type, "Run");
  44. if (!this.allEvents.ContainsKey(aEventAttribute.Type))
  45. {
  46. this.allEvents.Add(aEventAttribute.Type, new List<IInstanceMethod>());
  47. }
  48. this.allEvents[aEventAttribute.Type].Add(method);
  49. }
  50. }
  51. #endif
  52. }
  53. public void Run(int type, params object[] param)
  54. {
  55. List<IInstanceMethod> iEvents = null;
  56. if (!this.allEvents.TryGetValue(type, out iEvents))
  57. {
  58. return;
  59. }
  60. foreach (IInstanceMethod obj in iEvents)
  61. {
  62. try
  63. {
  64. obj.Run(param);
  65. }
  66. catch (Exception err)
  67. {
  68. Log.Error(err.ToString());
  69. }
  70. }
  71. }
  72. }
  73. }