首页 > 代码库 > foreach是怎么实现遍历的

foreach是怎么实现遍历的

using System;

using System.Collections;

using System.Collections.Generic;

using System.Linq; using System.Text;

using System.Threading.Tasks;

namespace ConsoleApplication2 {  

   class Program     {      

   static void Main(string[] args)       

  {            

Person per = new Person();           

  //如果直接遍历person,会提示person不包含getEnumrator的公共定义,所以foreach语句不能作用于person的变量       

      //foreach (string item in per)            

//{

//}           

  //当person实心了iEnumreble接口时,其实目的只是为了实现接口中的IEnumerator的方法,此时foreach不在冒红了         

    foreach (string item in per)           

  {                

Console.WriteLine(item);        

     }                      

           Console.Read();       

  }    

}   

 

  public class Person : IEnumerable   

  {       

  public string Name { get; set; }    

     public int Age { get; set; }     

    private string[] strArray = new string[] { "aaa", "bbb", "ccc", "ddd" };

 

    /// <summary> /// 这就是枚举器  /// </summary>      

   /// <returns></returns>       

  public IEnumerator GetEnumerator()        

{            

//返回实现了IEnumerator接口的枚举器            

return new PersonEnumrator(strArray);        

}

}    

/// <summary> /// 自己写一个枚举器,并且实现IEnumerator,然后需要重写IEnumerator中的方法 /// </summary>    

public class PersonEnumrator : IEnumerator    

{        

//声明数组        

string[] strArray;        

/// <summary> /// 构造函数,初始化数组  /// </summary>        

/// <param name="arr"></param>        

public PersonEnumrator(string[] arr)        

{           

  if (arr != null)                

strArray = arr;        

}        

int index = -1;//下标        

/// <summary>         /// 返回数组中下标为index的值         /// </summary>        

public object Current        

{            

get { return strArray[index]; }        

}        

/// <summary>         /// index自增一,判断index是否在数组的范围之内         /// </summary>        

/// <returns>在范围内,返回TRUE,否则返回FALSE</returns>        

public bool MoveNext()        

{            

index++;            

while (index < strArray.Length)            

{

                return true;            

}            

return false;        

}        

/// <summary>         /// 将下标重置         /// </summary>        

public void Reset()        

{            

index = -1;        

}     }

}