Config.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.IO;
  5. using Component;
  6. namespace World
  7. {
  8. public class Config
  9. {
  10. private static readonly Config instance = new Config();
  11. public static Config Instance
  12. {
  13. get
  14. {
  15. return instance;
  16. }
  17. }
  18. public Dictionary<string, object> allConfig;
  19. private Config()
  20. {
  21. this.Load();
  22. }
  23. private void Load()
  24. {
  25. this.allConfig = new Dictionary<string, object>();
  26. string currentDir = AppDomain.CurrentDomain.BaseDirectory;
  27. Type[] types = typeof(Config).Assembly.GetTypes();
  28. foreach (var type in types)
  29. {
  30. object[] attrs = type.GetCustomAttributes(typeof(ConfigAttribute), false);
  31. if (attrs.Length == 0)
  32. {
  33. continue;
  34. }
  35. object obj = (Activator.CreateInstance(type));
  36. var iInit = obj as IConfigInitialize;
  37. if (iInit == null)
  38. {
  39. throw new Exception(string.Format("class {0} is not IConfigInitialize", type.Name));
  40. }
  41. var iSupportInitialize = obj as ISupportInitialize;
  42. if (iSupportInitialize != null)
  43. {
  44. iSupportInitialize.BeginInit();
  45. }
  46. string configDir = Path.Combine(
  47. currentDir, ((ConfigAttribute)attrs[0]).RelativeDirectory);
  48. if (!Directory.Exists(configDir))
  49. {
  50. throw new Exception(string.Format("not found config dir: {0}", configDir));
  51. }
  52. iInit.Init(configDir);
  53. if (iSupportInitialize != null)
  54. {
  55. iSupportInitialize.EndInit();
  56. }
  57. allConfig[iInit.ConfigName] = obj;
  58. }
  59. }
  60. public void Reload()
  61. {
  62. this.Load();
  63. }
  64. public T Get<T>(int type) where T : IType
  65. {
  66. var configManager = (ConfigManager<T>)allConfig[typeof (T).Name];
  67. return configManager[type];
  68. }
  69. public Dictionary<int, T> GetAll<T>() where T : IType
  70. {
  71. var configManager = (ConfigManager<T>)allConfig[typeof (T).Name];
  72. return configManager.GetAll();
  73. }
  74. public ConfigManager<T> GetConfigManager<T>() where T : IType
  75. {
  76. return (ConfigManager<T>)allConfig[typeof(T).Name];
  77. }
  78. }
  79. }