private sealed class ReversibleSortedListKeyEnumerator :
IEnumerator<TKey>, IDisposable, IEnumerator
{
private ReversibleSortedList<TKey, TValue> _dict;
private TKey _currentKey;
private int _index, _version;
internal ReversibleSortedListKeyEnumerator(ReversibleSortedList<TKey, TValue> dict)
{ _dict = dict; _version = dict.version; }
public void Dispose() { _index = 0; _currentKey = default; }
public bool MoveNext()
{
if (_version != _dict.version) throw new InvalidOperationException("枚舉版本檢查錯誤");
if (_index < _dict.Count)
{ _currentKey = _dict.keys[_index]; _index++; return true; }
_index = _dict.Count + 1; _currentKey = default; return false;
}
void IEnumerator.Reset()
{
if (_version != _dict.version) throw new InvalidOperationException("枚舉版本檢查錯誤");
_index = 0; _currentKey = default;
}
public TKey Current => _currentKey;
object IEnumerator.Current
{
get
{
if (_index == 0 || _index == _dict.Count + 1) throw new InvalidOperationException("不能進行枚舉操作");
return _currentKey;
}
}
}
此列舉器直接讀取外部 keys 陣列,無需考慮排序方向(外部已維持有序)。同樣採用版本號機制偵測並發修改。