ConfigComponent.cs 2.2 KB

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