ACategory.cs 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. namespace Base
  6. {
  7. /// <summary>
  8. /// 管理该所有的配置
  9. /// </summary>
  10. /// <typeparam name="T"></typeparam>
  11. public abstract class ACategory<T>: ICategory where T : AConfig
  12. {
  13. protected Dictionary<long, T> dict;
  14. public virtual void BeginInit()
  15. {
  16. this.dict = new Dictionary<long, T>();
  17. string path = $@"Config/{typeof (T).Name}";
  18. string configStr;
  19. try
  20. {
  21. configStr = File.ReadAllText(path);
  22. }
  23. catch (Exception)
  24. {
  25. throw new Exception($"load config file fail, path: {path}");
  26. }
  27. foreach (string str in configStr.Split(new[] { "\r\n" }, StringSplitOptions.None))
  28. {
  29. try
  30. {
  31. string str2 = str.Trim();
  32. if (str2 == "")
  33. {
  34. continue;
  35. }
  36. T t = MongoHelper.FromJson<T>(str2);
  37. this.dict.Add(t.Id, t);
  38. }
  39. catch (Exception e)
  40. {
  41. throw new Exception($"parser json fail: {str}", e);
  42. }
  43. }
  44. }
  45. public Type ConfigType
  46. {
  47. get
  48. {
  49. return typeof (T);
  50. }
  51. }
  52. public virtual void EndInit()
  53. {
  54. }
  55. public T this[long type]
  56. {
  57. get
  58. {
  59. T t;
  60. if (!this.dict.TryGetValue(type, out t))
  61. {
  62. throw new Exception($"{typeof (T)} 没有找到配置, key: {type}");
  63. }
  64. return t;
  65. }
  66. }
  67. public T TryGet(int type)
  68. {
  69. T t;
  70. if (!this.dict.TryGetValue(type, out t))
  71. {
  72. return null;
  73. }
  74. return t;
  75. }
  76. public T[] GetAll()
  77. {
  78. return this.dict.Values.ToArray();
  79. }
  80. public T GetOne()
  81. {
  82. return this.dict.Values.First();
  83. }
  84. }
  85. }