ConfigComponent.cs 2.6 KB

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