ConfigComponent.cs 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  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>, IAssemblyLoader
  9. {
  10. public Dictionary<Type, ICategory> allConfig;
  11. public void Load(Assembly assembly)
  12. {
  13. this.allConfig = new Dictionary<Type, ICategory>();
  14. Type[] types = assembly.GetTypes();
  15. foreach (Type type in types)
  16. {
  17. object[] attrs = type.GetCustomAttributes(typeof (ConfigAttribute), false);
  18. if (attrs.Length == 0)
  19. {
  20. continue;
  21. }
  22. object obj = (Activator.CreateInstance(type));
  23. ICategory iCategory = obj as ICategory;
  24. if (iCategory == null)
  25. {
  26. throw new Exception(string.Format("class: {0} not inherit from ACategory", type.Name));
  27. }
  28. iCategory.BeginInit();
  29. iCategory.EndInit();
  30. this.allConfig[iCategory.ConfigType] = iCategory;
  31. }
  32. }
  33. public T Get<T>(int id) where T : AConfig
  34. {
  35. Type type = typeof (T);
  36. ICategory configCategory;
  37. if (!this.allConfig.TryGetValue(type, out configCategory))
  38. {
  39. throw new KeyNotFoundException(string.Format("ConfigComponent not found key: {0}", type.FullName));
  40. }
  41. return ((ACategory<T>) configCategory)[id];
  42. }
  43. public T[] GetAll<T>() 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).GetAll();
  52. }
  53. public T GetCategory<T>() where T : class, ICategory, new()
  54. {
  55. T t = new T();
  56. Type type = t.ConfigType;
  57. ICategory category;
  58. bool ret = this.allConfig.TryGetValue(type, out category);
  59. return ret? (T) category : null;
  60. }
  61. }
  62. }