參考網址:https://blog.csdn.net/qq_39806817/article/details/115024666
一、IEnumerable簡單介紹
IEnumerable是可枚舉類型,一般在疊代時應用廣泛,如foreach中要循環通路的集合或數組都實作了IEnumerable接口。隻要能夠周遊,都直接或間接實作了IEnumerable接口。如:String類型的對象,可周遊,輸出時以字元輸出,間接實作了IEnumerable接口,"OOP"周遊列印就是'O','O','P';又如int類型沒有實作IEnumerable接口,就無法依賴foreach周遊。
二、實作IEnumerable接口
現以一個執行個體周遊數組:
IEnumerableTest enumerableTest = new IEnumerableTest();
enumerableTest.Show();
-------------------------------------------------------
public class IEnumerableTest
{
DemoIEnumerable demoIEnumerable = new DemoIEnumerable();
public void Show()
{
foreach (var item in demoIEnumerable)
{
Console.WriteLine(item);
}
}
}
public class DemoIEnumerable : IEnumerable
public IEnumerator GetEnumerator()
string[] students = new[] { "瑤瑤1", "瑤瑤2", "瑤瑤3" };
return new TestEnumerator(students);
public class TestEnumerator : IEnumerator
private string[] _students;
//元素下标
private int _position = -1;
public TestEnumerator(string[] students)
this._students = students;
//public object Current => throw new NotImplementedException();
public object Current
get
if (_position == -1 || _position >= _students.Length)
{
throw new InvalidOperationException();
}
return _students[_position];
public bool MoveNext()
if (_position < _students.Length - 1)
_position++;
return true;
return false;
public void Reset()
_position = -1;
上面的執行個體執行foreach步驟:首先進入DemoIEnumerable類執行GetEnumerator()方法,然後初始化_position=-1,接着執行TestEnumerator類的構造函數,然後傳回進入in,執行TestEnumerator類的MoveNext()方法,判斷下标(_position)是否越界,如沒有越界,下标自動加1,并傳回true,然後擷取TestEnumerator類的Current屬性,傳回對應下标的值,依次疊代,擷取數組的值,直至結束。