不用管它是什麼類型,只是實現了IEnumerable接口都可以迭代
public interface IEnumerable
{
IEnumerator GetEnumerator();// 返回一個 IEnumerator 變量
}
public interface IEnumerator
{
object Current { get; } //返回當前元素,相當於 return arr[currIndex]
bool MoveNext(); //下標加1然後返回當前下標是否超出容器長度
void Reset(); //下標變成-1,相當於 currIndex=-1;
}
int[] arr = {1,2,3,4,5};
int currIndex = -1; //當前下標 , IEnumerator迭代前 當前下標是-1
//====以arr爲例解釋IEnumerator接口方法的意思
object Current //返回當前元素
{
get
{ //判斷下標是否超出容器區間外
if(currIndex < 0 || currIndex >= arr.Length) return null; //或者拋出異常
return arr[currIndex];
}
}
bool MoveNext() //下標加1然後返回當前下標是否超出容器長度
{
currIndex++;
return currIndex < arr.Length;
}
void Reset()//下標變成-1,相當於 currIndex=-1;
{
currIndex=-1;
}
foreach 變形 while遍歷
IEnumerator enumerator = arr.GetEnumerator();
while (enumerator.MoveNext())
{
int item = (int)enumerator.Current;
Console.WriteLine(item);
}
IEnumerator 轉 list , foreach遍歷 轉 for遍歷
int[] arr = { 1, 2, 3, 4, 5 };
IEnumerator enumerator = arr.GetEnumerator();
var list = new List<int>();
while (enumerator.MoveNext()) //IEnumerator迭代前 當前下標是-1
{
int item = (int) enumerator.Current;
list.Add(item);
}
//實現從foreach遍歷 到 for遍歷
for (int i = 0; i < list.Count; i++)
{
Debug.Log(list[i]);
}
名稱 | 別名 | using | NuGet包 | 內容 |
Linq | using System.Linq; | 迭代器 擴展操作 | ||
System.Interactive | Linq 擴展 | |||
Reactive Extensions |
Rx | using System.Reactive.Linq; | System.Reactive | Linq 擴展 |
UniRx | Unity3d 上的 Rx |