C# 中的 IEnumerator 和 IEnumerable 介面之間的差異


IEnumerable和IEnumerator在C#中都是介面。

IEnumerable是一個介面,定義一個方法 GetEnumerator(),它返回一個 IEnumerator 介面。

這適用於對實現 IEnumerable 的集合進行只讀訪問,可以使用 foreach 語句。

IEnumerator有兩個方法MoveNext和Reset。它還有個屬性叫做Current。

以下顯示了IEnumerable和IEnumerator的實現。

示例

class Demo : IEnumerable, IEnumerator {
   // IEnumerable method GetEnumerator()
   IEnumerator IEnumerable.GetEnumerator() {
      throw new NotImplementedException();
   }
   public object Current {
      get { throw new NotImplementedException(); }
   }
   // IEnumertor method
   public bool MoveNext() {
      throw new NotImplementedException();
   }
   // IEnumertor method
      public void Reset() {
      throw new NotImplementedException();
   }
}

上面你可以看到IEnumerator的兩個方法。

// IEnumertor method
public bool MoveNext() {
   throw new NotImplementedException();
}

// IEnumertor method
public void Reset() {
   throw new NotImplementedException();
}

更新於: 2020年6月23日

6K+ 瀏覽次數

開啟你的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.