ACategory.cs 1.4 KB

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