You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

90 lines
2.1 KiB

  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Security.AccessControl;
  5. using System.Text;
  6. namespace Apewer
  7. {
  8. /// <summary></summary>
  9. public sealed class Enumerator<T> : IEnumerator<T>, IEnumerator, IDisposable
  10. {
  11. // 类的状态
  12. bool _disposed = false;
  13. string _type;
  14. // 元素获取
  15. Func<int, Class<T>> _getter = null;
  16. // 迭代器
  17. int _index = 0;
  18. T _current = default;
  19. #region IDisposable
  20. /// <summary></summary>
  21. public void Dispose()
  22. {
  23. _disposed = true;
  24. }
  25. #endregion
  26. #region IEnumerator<T>
  27. /// <summary></summary>
  28. public T Current
  29. {
  30. get
  31. {
  32. if (_disposed) throw new ObjectDisposedException(_type);
  33. return _current;
  34. }
  35. }
  36. #endregion
  37. #region IEnumerator
  38. /// <summary></summary>
  39. object IEnumerator.Current { get => Current; }
  40. /// <summary></summary>
  41. public bool MoveNext()
  42. {
  43. if (_disposed) throw new ObjectDisposedException(_type);
  44. var value = _getter(_index);
  45. if (value == null) return false;
  46. _current = value.Value;
  47. _index++;
  48. return true;
  49. }
  50. /// <summary></summary>
  51. public void Reset()
  52. {
  53. if (_disposed) throw new ObjectDisposedException(_type);
  54. _current = default;
  55. _index = 0;
  56. }
  57. #endregion
  58. /// <summary>创建枚举器实例。</summary>
  59. /// <param name="getter">元素获取程序。传入参数为索引值,从 0 开始;枚举结束后应返回 NULL 值。</param>
  60. /// <exception cref="ArgumentNullException" />
  61. public Enumerator(Func<int, Class<T>> getter)
  62. {
  63. if (getter == null) throw new ArgumentNullException(nameof(getter));
  64. _getter = getter;
  65. _type = GetType().Name;
  66. Reset();
  67. }
  68. }
  69. }