前言
- 前段時間看c#迭代器的實現,心裏很着急,完全靜不下來,所以也沒有看懂
- 最近抽時間看了一下C#迭代器的接口設計,然後就理解了
核心
- 迭代器的本質就是內部保存對源數據的一個索引,然後具有一個遊標CurrIndx,每次MoveNext都會移動該遊標一下,Curent就是返回當前遊標位置的數據
- C#的IEnumerable 接口需要實現方法GetEnumerator() 返回Enumerator
- 而IEnumerator接口則定義了迭代器的必要實現,MoveNext()方法 Current屬性,Reset()方法
- yield 本身是C#的一個語法糖,簡化了迭代器的實現,他將新創建一個迭代器類,內部保存了 yield return 的數據
- yield break 可以打斷,類似於return
- 所以我們如果要創建迭代器就可以用下面這樣
public Class StudentList:IEnumerable{
private Student[] dataTable;
public Enumerator GetEnumerator(){
for(int i=0; i< dataTable.Length;i++){
yield return dataTable[i];
}
}
}
自己動手實現
- 這裏public T this[int index] 的實現很有意思
public class ListEx<T>
{
private T[] dataTable;
public int count;
public ListEx(){
dataTable = new T[16];
count = 0;
}
public T this[int index]
{
get { return dataTable[index]; }
set { dataTable[index] = value;count++;}
}
public EnumeratorEx<T> GetEnumerator()
{
return new EnumeratorEx<T>(this);
}
}
public class EnumeratorEx<T>
{
private ListEx<T> collection;
public EnumeratorEx(ListEx<T> collection)
{
this.collection = collection;
Reset();
}
private void Reset()
{
currIndex = -1;
}
private int currIndex;
public bool MoveNext()
{
currIndex++;
if (currIndex >= collection.count)
{
return false;
}
return true;
}
public T Current
{
get { return collection[currIndex]; }
}
}
ListEx<int> ex = new ListEx<int>();
ex[0]=1;
ex[1]=2;
ex[2]=3;
EnumeratorEx<int> enumerator = ex.GetEnumerator();
while (enumerator.MoveNext())
{
Debug.Log(enumerator.Current);
}
參考鏈接
- https://blog.csdn.net/mango_love/article/details/84935723
- https://blog.csdn.net/qq_36576410/article/details/86690605