ConfigComponent.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. namespace Model
  5. {
  6. [ObjectEvent]
  7. public class ConfigComponentEvent : ObjectEvent<ConfigComponent>, ILoad
  8. {
  9. public void Load()
  10. {
  11. this.Get().Load();
  12. }
  13. }
  14. public class ConfigComponent: Component
  15. {
  16. private Dictionary<Type, ICategory> allConfig;
  17. public void Load()
  18. {
  19. Assembly assembly = ObjectEvents.Instance.GetAssembly("Model");
  20. this.allConfig = new Dictionary<Type, ICategory>();
  21. Type[] types = assembly.GetTypes();
  22. foreach (Type type in types)
  23. {
  24. object[] attrs = type.GetCustomAttributes(typeof (ConfigAttribute), false);
  25. if (attrs.Length == 0)
  26. {
  27. continue;
  28. }
  29. object obj = Activator.CreateInstance(type);
  30. ICategory iCategory = obj as ICategory;
  31. if (iCategory == null)
  32. {
  33. throw new Exception($"class: {type.Name} not inherit from ACategory");
  34. }
  35. iCategory.BeginInit();
  36. iCategory.EndInit();
  37. this.allConfig[iCategory.ConfigType] = iCategory;
  38. }
  39. }
  40. public T GetOne<T>() where T : AConfig
  41. {
  42. Type type = typeof (T);
  43. if (!this.allConfig.TryGetValue(type, out ICategory configCategory))
  44. {
  45. throw new Exception($"ConfigComponent not found key: {type.FullName}");
  46. }
  47. return ((ACategory<T>) configCategory).GetOne();
  48. }
  49. public T Get<T>(long id) where T : AConfig
  50. {
  51. Type type = typeof (T);
  52. if (!this.allConfig.TryGetValue(type, out ICategory configCategory))
  53. {
  54. throw new Exception($"ConfigComponent not found key: {type.FullName}");
  55. }
  56. return ((ACategory<T>) configCategory)[id];
  57. }
  58. public T TryGet<T>(int id) where T : AConfig
  59. {
  60. Type type = typeof (T);
  61. if (!this.allConfig.TryGetValue(type, out ICategory configCategory))
  62. {
  63. return default(T);
  64. }
  65. return ((ACategory<T>) configCategory).TryGet(id);
  66. }
  67. public T[] GetAll<T>() where T : AConfig
  68. {
  69. Type type = typeof (T);
  70. if (!this.allConfig.TryGetValue(type, out ICategory configCategory))
  71. {
  72. throw new Exception($"ConfigComponent not found key: {type.FullName}");
  73. }
  74. return ((ACategory<T>) configCategory).GetAll();
  75. }
  76. public T GetCategory<T>() where T : class, ICategory, new()
  77. {
  78. T t = new T();
  79. Type type = t.ConfigType;
  80. bool ret = this.allConfig.TryGetValue(type, out ICategory category);
  81. return ret? (T) category : null;
  82. }
  83. }
  84. }