MapperConfigurationCollectionContainer.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. namespace Masuit.Tools.Mapping.Core
  6. {
  7. /// <summary>
  8. /// 单例存储映射器。
  9. /// </summary>
  10. /// <remarks>不需要单例,因为适用于所有线程。</remarks>
  11. public class MapperConfigurationCollectionContainer : IEnumerable<MapperConfigurationBase>
  12. {
  13. private readonly HashSet<MapperConfigurationBase> _items;
  14. private static MapperConfigurationCollectionContainer currentInstance;
  15. private MapperConfigurationCollectionContainer()
  16. {
  17. _items = new HashSet<MapperConfigurationBase>();
  18. }
  19. public static MapperConfigurationCollectionContainer Instance => currentInstance ?? (currentInstance = new MapperConfigurationCollectionContainer());
  20. public int Count => _items.Count;
  21. internal MapperConfigurationBase this[int index]
  22. {
  23. get
  24. {
  25. if (index > _items.Count)
  26. throw new IndexOutOfRangeException();
  27. var enumerator = GetEnumerator();
  28. int i = 0;
  29. while (enumerator.MoveNext())
  30. {
  31. if (i == index)
  32. {
  33. return enumerator.Current;
  34. }
  35. i++;
  36. }
  37. return null;
  38. }
  39. }
  40. /// <summary>
  41. /// 查找指定的源。
  42. /// </summary>
  43. /// <param name="source">源类型</param>
  44. /// <param name="target">目标对象</param>
  45. /// <param name="name">别名</param>
  46. internal MapperConfigurationBase Find(Type source, Type target, string name = null)
  47. {
  48. foreach (var current in this)
  49. {
  50. string nameMapper = string.IsNullOrEmpty(name) ? current.paramClassSource.Name : name;
  51. if (current.SourceType == source && current.TargetType == target && current.Name == nameMapper)
  52. {
  53. return current;
  54. }
  55. }
  56. return null;
  57. }
  58. /// <summary>
  59. /// 是否存在谓词的映射。
  60. /// </summary>
  61. /// <param name="match">条件表达式</param>
  62. public bool Exists(Func<MapperConfigurationBase, bool> match)
  63. {
  64. return this.Any(match);
  65. }
  66. public void RemoveAt(int index)
  67. {
  68. MapperConfigurationBase itemToDelete = this[index];
  69. if (itemToDelete != null)
  70. {
  71. _items.Remove(itemToDelete);
  72. }
  73. }
  74. /// <summary>
  75. /// 清除
  76. /// </summary>
  77. public void Clear()
  78. {
  79. _items.Clear();
  80. }
  81. public void Add(MapperConfigurationBase value)
  82. {
  83. _items.Add(value);
  84. }
  85. public IEnumerator<MapperConfigurationBase> GetEnumerator()
  86. {
  87. return _items.GetEnumerator();
  88. }
  89. IEnumerator IEnumerable.GetEnumerator()
  90. {
  91. return GetEnumerator();
  92. }
  93. }
  94. }