ConfigComponent.cs 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. if (!this.allConfig.TryGetValue(type, out ICategory configCategory))
  35. {
  36. throw new Exception($"ConfigComponent not found key: {type.FullName}");
  37. }
  38. return ((ACategory<T>) configCategory).GetOne();
  39. }
  40. public T Get<T>(long id) 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)[id];
  48. }
  49. public T TryGet<T>(int id) where T : AConfig
  50. {
  51. Type type = typeof (T);
  52. if (!this.allConfig.TryGetValue(type, out ICategory configCategory))
  53. {
  54. return default(T);
  55. }
  56. return ((ACategory<T>) configCategory).TryGet(id);
  57. }
  58. public T[] GetAll<T>() where T : AConfig
  59. {
  60. Type type = typeof (T);
  61. if (!this.allConfig.TryGetValue(type, out ICategory configCategory))
  62. {
  63. throw new Exception($"ConfigComponent not found key: {type.FullName}");
  64. }
  65. return ((ACategory<T>) configCategory).GetAll();
  66. }
  67. public T GetCategory<T>() where T : class, ICategory, new()
  68. {
  69. T t = new T();
  70. Type type = t.ConfigType;
  71. bool ret = this.allConfig.TryGetValue(type, out ICategory category);
  72. return ret? (T) category : null;
  73. }
  74. }
  75. }