1. 程式人生 > 其它 >C#中IEumerable的簡單瞭解

C#中IEumerable的簡單瞭解

參考網址: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屬性,返回對應下標的值,依次迭代,獲取陣列的值,直至結束。