ConfigComponent.cs 2.2 KB

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