可以看到,實現它 並不簡單,好在我們將屏蔽所有對元素進行改動的功能。當然,首先還是要要實現一個枚舉器(感覺又回到了第2節: http://cgbluesky.blog.163.com/blog/static/241235582008113103320661/ ),不同的地方在於,這次枚舉器跟調用類的關系不再是嵌套關 系,它們處於同一層次,都是ReversibleSortedList的嵌套類。另外由於引用外部類集合,這裡也不需要考慮反向排序的問題。
下面是 Keys屬性枚舉時所需要的枚舉器:
#region ReversibleSortedListKeyEnumerator
private sealed class ReversibleSortedListKeyEnumerator :
IEnumerator<TKey>, IDisposable, IEnumerator
{
// 成員變量
private ReversibleSortedList<TKey, TValue> _ReversibleSortedList;
private TKey currentKey; //記錄當前值
private int index; //記錄當前索引
private int version; //記錄此類創建時, 外部類的版本號
//構造方法
internal ReversibleSortedListKeyEnumerator(
ReversibleSortedList<TKey, TValue> ReversibleSortedList)
{ //傳遞外部類元素所在集合的引用
this._ReversibleSortedList = ReversibleSortedList;
this.version = ReversibleSortedList.version;
}
public void Dispose()
{
this.index = 0;
this.currentKey = default(TKey);
}
public bool MoveNext()
{
if (this.version != this._ReversibleSortedList.version)
{
throw new InvalidOperationException(
"枚舉版本檢查錯誤");
}
if (this.index < this._ReversibleSortedList.Count)
{
this.currentKey = this._ReversibleSortedList.keys [this.index];
this.index++;
return true;
}
this.index = this._ReversibleSortedList.Count + 1;
this.currentKey = default(TKey);
return false;
}
void IEnumerator.Reset()
{
if (this.version != this._ReversibleSortedList.version)
{
throw new InvalidOperationException(
"枚舉版本檢查錯誤");
}
this.index = 0;
this.currentKey = default(TKey);
}
// 屬性
public TKey Current
{
get
{
return this.currentKey;
}
}
object IEnumerator.Current
{
get
{
if ((this.index == 0) || (this.index ==
(this._ReversibleSortedList.Count + 1)))
{
throw new InvalidOperationException(
"不能進行枚舉操作");
}
return this.currentKey;
}
}
}
#endregion