ConfigManager.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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",
  25. type.Name));
  26. }
  27. iCategory.BeginInit();
  28. iCategory.EndInit();
  29. localAllConfig[type.Name] = obj;
  30. }
  31. this.allConfig = localAllConfig;
  32. }
  33. public T Get<T>(int type) where T : IConfig
  34. {
  35. var configCategory = (ACategory<T>) this.allConfig[typeof (T).Name];
  36. return configCategory[type];
  37. }
  38. public T[] GetAll<T>() where T : IConfig
  39. {
  40. var configCategory = (ACategory<T>) this.allConfig[typeof (T).Name];
  41. return configCategory.GetAll();
  42. }
  43. public T GetCategory<T>() where T : class, ICategory, new()
  44. {
  45. T t = new T();
  46. object category;
  47. bool ret = this.allConfig.TryGetValue(t.Name, out category);
  48. return ret? (T) category : null;
  49. }
  50. }
  51. }