InjectModule.InjectMap.cs 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. using System;
  2. using System.Collections.Generic;
  3. namespace IFramework.Inject
  4. {
  5. public partial class InjectModule
  6. {
  7. private class InjectMap<T>
  8. {
  9. public class Value : IValueContainer<T>
  10. {
  11. public string key;
  12. public T value { get; set; }
  13. }
  14. protected List<Value> containers;
  15. protected Dictionary<Type, List<int>> map;
  16. public InjectMap()
  17. {
  18. containers = new List<Value>();
  19. map = new Dictionary<Type, List<int>>();
  20. }
  21. public void Set(Type super, string key, T t)
  22. {
  23. List<int> list;
  24. if (!map.TryGetValue(super, out list))
  25. {
  26. list = new List<int>();
  27. map.Add(super, list);
  28. }
  29. for (int i = list.Count - 1; i >= 0; i--)
  30. {
  31. int index = list[i];
  32. var value = containers[index];
  33. if (value.key == key)
  34. {
  35. value.value = t;
  36. return;
  37. }
  38. }
  39. list.Add(containers.Count);
  40. containers.Add(new Value() { key = key, value = t });
  41. }
  42. public T Get(Type super, string key)
  43. {
  44. List<int> list;
  45. if (map.TryGetValue(super, out list))
  46. {
  47. for (int i = list.Count - 1; i >= 0; i--)
  48. {
  49. int index = list[i];
  50. var value = containers[index];
  51. if (value.key == key)
  52. {
  53. return value.value;
  54. }
  55. }
  56. }
  57. return default(T);
  58. }
  59. protected T GetByindex(int index)
  60. {
  61. return containers[index].value;
  62. }
  63. public void Clear()
  64. {
  65. map.Clear();
  66. containers.Clear();
  67. }
  68. public IEnumerable<T> Values
  69. {
  70. get
  71. {
  72. for (int i = 0; i < containers.Count; i++)
  73. {
  74. yield return GetByindex(i);
  75. }
  76. }
  77. }
  78. }
  79. }
  80. }