從代碼中可以看出,它 把外部類中的所有元素拷貝到另一塊內存中進行枚舉,這樣在多線程訪問集合時 自然不會出錯,但如果集合中的元素很多就會帶來性能上的損失。而我們實現的 ReversibleSortedList類將直接使用集合中的元素進行枚舉,所以需要使用 version來保證在出錯時可以彈出異常。
下面我們在 “ReversibleSortedList 0.3版本”的基礎上繼續構建。關於 version的代碼這裡不再講解,請大家查看稍後完整的0.4版本的代碼。首先添加 一個實現枚舉器的嵌套類:
private struct Enumerator<K, V> : IEnumerator<KeyValuePair<K, V>>, IDisposable,
IDictionaryEnumerator, IEnumerator
{
private ReversibleSortedList<K, V> _ReversibleSortedList;
private K key;
private V value;
private int index;
private int version;
internal Enumerator(ReversibleSortedList<K, V> ReversibleSortedList)
{ //獲取外部類中的元素引用,以對 它進行枚舉
this._ReversibleSortedList = ReversibleSortedList;
this.index = 0;
this.version = this._ReversibleSortedList.version;//記錄外部類版本號
//設置鍵和值為其默認類型,請參考:
//http://cgbluesky.blog.163.com/blog/static/2412355820081695340822/
this.key = default(K);
this.value = default(V);
}
public void Dispose()
{
this.index = 0;
this.key = default(K);
this.value = default(V);
}
object IDictionaryEnumerator.Key
{
get
{
if ((this.index == 0) ||
(this.index == (this._ReversibleSortedList.Count + 1)))
{
throw new InvalidOperationException(
"不能進行枚舉操作.");
}
return this.key;
}
}
public bool MoveNext()
{
if (this.version != this._ReversibleSortedList.version)
{ //版本檢查
throw new InvalidOperationException("枚舉版本檢查失敗!");
}
if (this.index < this._ReversibleSortedList.Count)
{
this.key = this._ReversibleSortedList.keys[this.index];
this.value = this._ReversibleSortedList.values [this.index];
this.index++;
return true;
}
this.index = this._ReversibleSortedList.Count + 1;
this.key = default(K);
this.value = default(V);
return false;
}
DictionaryEntry IDictionaryEnumerator.Entry
{
get
{
if ((this.index == 0) ||
(this.index == (this._ReversibleSortedList.Count + 1)))
{
throw new InvalidOperationException("不能進行枚舉操作.");
}
return new DictionaryEntry(this.key, this.value);
}
}
public KeyValuePair<K, V> Current
{
get
{
return new KeyValuePair<K, V>(this.key, this.value);
}
}
object IEnumerator.Current
{
get
{
if ((this.index == 0) ||
(this.index == (this._ReversibleSortedList.Count + 1)))
{
throw new InvalidOperationException("不能進行 枚舉操作");
}
return new DictionaryEntry(this.key, this.value);
}
}
object IDictionaryEnumerator.Value
{
get
{
if ((this.index == 0) ||
(this.index == (this._ReversibleSortedList.Count + 1)))
{
throw new InvalidOperationException("不能進行 枚舉操作");
}
return this.value;
}
}
void IEnumerator.Reset()
{
if (this.version != this._ReversibleSortedList.version)
{
throw new InvalidOperationException("枚舉版本檢查失敗! ");
}
this.index = 0;
this.key = default(K);
this.value = default (V);
}
}