ConfigComponent.cs 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Reflection;
  4. using Common.Base;
  5. namespace Model
  6. {
  7. public class ConfigComponent: Component<World>, IAssemblyLoader
  8. {
  9. private Dictionary<Type, ICategory> allConfig;
  10. public void Load(Assembly assembly)
  11. {
  12. this.allConfig = new Dictionary<Type, ICategory>();
  13. Type[] types = assembly.GetTypes();
  14. ServerType serverType = World.Instance.Options.ServerType;
  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. ConfigAttribute configAttribute = (ConfigAttribute) attrs[0];
  23. if (!configAttribute.Contains(serverType))
  24. {
  25. continue;
  26. }
  27. object obj = (Activator.CreateInstance(type));
  28. ICategory iCategory = obj as ICategory;
  29. if (iCategory == null)
  30. {
  31. throw new Exception(string.Format("class: {0} not inherit from ACategory", type.Name));
  32. }
  33. iCategory.BeginInit();
  34. iCategory.EndInit();
  35. this.allConfig[iCategory.ConfigType] = iCategory;
  36. }
  37. }
  38. public T Get<T>(int id) where T : AConfig
  39. {
  40. Type type = typeof (T);
  41. ICategory configCategory;
  42. if (!this.allConfig.TryGetValue(type, out configCategory))
  43. {
  44. throw new KeyNotFoundException(string.Format("ConfigComponent not found key: {0}", type.FullName));
  45. }
  46. return ((ACategory<T>) configCategory)[id];
  47. }
  48. public T[] GetAll<T>() where T : AConfig
  49. {
  50. Type type = typeof (T);
  51. ICategory configCategory;
  52. if (!this.allConfig.TryGetValue(type, out configCategory))
  53. {
  54. throw new KeyNotFoundException(string.Format("ConfigComponent not found key: {0}", type.FullName));
  55. }
  56. return ((ACategory<T>) configCategory).GetAll();
  57. }
  58. public T GetCategory<T>() where T : class, ICategory, new()
  59. {
  60. T t = new T();
  61. Type type = t.ConfigType;
  62. ICategory category;
  63. bool ret = this.allConfig.TryGetValue(type, out category);
  64. return ret? (T) category : null;
  65. }
  66. }
  67. }