IEnumerabl 和 IEnumertator

  1. public interface IEnumerable  
  2. {  
  3.     IEnumerator GetEnumerator();  
  4. }  

IEnumerator 接口

  1. public interface IEnumerator  
  2. {  
  3.     bool MoveNext();  
  4.     object Current { get; }  
  5.     void Reset();  
  6. }  

实现IEnumerable接口的话需要实现其 IEnumerator.GetEnumerator 方法,其后也是需要实现 IEnumerator接口的方法(迭代模板)

  1. public class ListEnumerator : IEnumerator  
  2. {  
  3.     private int _currentIndex = -1;   
  4.      
  5.     public bool MoveNext()  
  6.     {  
  7.         _currentIndex++;  
  8.      
  9.         return (_currentIndex < _objects.Count);   
  10.     }  
  11.      
  12.     public object Current  
  13.     {   
  14.         get  
  15.         {  
  16.             try  
  17.             {  
  18.                 return _objects[_currentIndex];  
  19.             }  
  20.             catch (IndexOutOfRangeException)  
  21.             {  
  22.                 throw new InvalidOperationException();  
  23.             }  
  24.     }  
  25.      
  26.     public void Reset()  
  27.     {  
  28.         _currentIndex = -1;  
  29.     }  

 

c#

所有集合(列表字典堆栈队列)可枚举的,因为它们实现IEnumerable接口所以字符串 可以使用foreach遍历字符串字符串每个字符

 

原文地址:https://www.cnblogs.com/ILoveMyJob/p/10786808.html