private struct Enumerator<K, V> :
IEnumerator<KeyValuePair<K, V>>, IDisposable,
IDictionaryEnumerator, IEnumerator
{
private ReversibleSortedList<K, V> _list;
private K _key; private V _value;
private int _index, _version;
internal Enumerator(ReversibleSortedList<K, V> list)
{
_list = list; _index = 0; _version = list.version;
_key = default(K); _value = default(V);
}
public void Dispose() { _index = 0; _key = default(K); _value = default(V); }
// IDictionaryEnumerator.Key
object IDictionaryEnumerator.Key
{
get
{
if (_index == 0 || _index == _list.Count + 1)
throw new InvalidOperationException("無法列舉。");
return _key;
}
}
public bool MoveNext() { /* 見上節 */ }
// IDictionaryEnumerator.Entry
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
if (_index == 0 || _index == _list.Count + 1)
throw new InvalidOperationException("無法列舉。");
return new DictionaryEntry(_key, _value);
}
}
// IEnumerator.Current
public KeyValuePair<K, V> Current => new KeyValuePair<K, V>(_key, _value);
// IEnumerator.Current (非泛型)
object IEnumerator.Current
{
get
{
if (_index == 0 || _index == _list.Count + 1)
throw new InvalidOperationException("無法列舉。");
return new DictionaryEntry(_key, _value);
}
}
// IDictionaryEnumerator.Value
object IDictionaryEnumerator.Value
{
get
{
if (_index == 0 || _index == _list.Count + 1)
throw new InvalidOperationException("無法列舉。");
return _value;
}
}
void IEnumerator.Reset()
{
if (_version != _list.version)
throw new InvalidOperationException("列舉版本檢查失敗!");
_index = 0; _key = default(K); _value = default(V);
}
}
此設計直接引用外部陣列元素,避免複製帶來的效能損耗;版本機制確保集合異動時列舉器即時拋出例外。