ConfigManager.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. namespace Common.Config
  5. {
  6. public class ConfigManager
  7. {
  8. public Dictionary<string, object> allConfig;
  9. public void Load(Assembly assembly)
  10. {
  11. var localAllConfig = new Dictionary<string, object>();
  12. Type[] types = assembly.GetTypes();
  13. foreach (var type in types)
  14. {
  15. object[] attrs = type.GetCustomAttributes(typeof (ConfigAttribute), false);
  16. if (attrs.Length == 0)
  17. {
  18. continue;
  19. }
  20. object obj = (Activator.CreateInstance(type));
  21. ICategory iCategory = obj as ICategory;
  22. if (iCategory == null)
  23. {
  24. throw new Exception(string.Format("class: {0} not inherit from ACategory", type.Name));
  25. }
  26. iCategory.BeginInit();
  27. iCategory.EndInit();
  28. localAllConfig[type.Name] = obj;
  29. }
  30. this.allConfig = localAllConfig;
  31. }
  32. public T Get<T>(int type) where T : IConfig
  33. {
  34. var configCategory = (ACategory<T>)this.allConfig[typeof(T).Name];
  35. return configCategory[type];
  36. }
  37. public T[] GetAll<T>() where T : IConfig
  38. {
  39. var configCategory = (ACategory<T>)this.allConfig[typeof(T).Name];
  40. return configCategory.GetAll();
  41. }
  42. public T GetCategory<T>() where T : class, ICategory, new()
  43. {
  44. T t = new T();
  45. object category;
  46. bool ret = this.allConfig.TryGetValue(t.Name, out category);
  47. return ret? (T) category : null;
  48. }
  49. }
  50. }