ConfigComponent.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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. public void Load(Assembly assembly)
  12. {
  13. 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(
  27. string.Format("class: {0} not inherit from ACategory", type.Name));
  28. }
  29. iCategory.BeginInit();
  30. iCategory.EndInit();
  31. allConfig[iCategory.ConfigType] = iCategory;
  32. }
  33. }
  34. public T Get<T>(int id) where T : AConfig
  35. {
  36. Type type = typeof (T);
  37. ICategory configCategory;
  38. if (!this.allConfig.TryGetValue(type, out configCategory))
  39. {
  40. throw new KeyNotFoundException(string.Format("ConfigComponent not found key: {0}", type.FullName));
  41. }
  42. return ((ACategory<T>) configCategory)[id];
  43. }
  44. public T[] GetAll<T>() where T : AConfig
  45. {
  46. Type type = typeof(T);
  47. ICategory configCategory;
  48. if (!this.allConfig.TryGetValue(type, out configCategory))
  49. {
  50. throw new KeyNotFoundException(string.Format("ConfigComponent not found key: {0}", type.FullName));
  51. }
  52. return ((ACategory<T>)configCategory).GetAll();
  53. }
  54. public T GetCategory<T>() where T : class, ICategory, new()
  55. {
  56. T t = new T();
  57. Type type = t.ConfigType;
  58. ICategory category;
  59. bool ret = this.allConfig.TryGetValue(type, out category);
  60. return ret? (T) category : null;
  61. }
  62. }
  63. }