ConfigComponent.cs 2.3 KB

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