ConfigComponent.cs 2.3 KB

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