ConfigComponent.cs 2.2 KB

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