C# foreach循环实例详解

发布时间:2010年10月25日      浏览次数:662 次
在编写C#代码时,我们会发现使用foreach循环会比使用for循环方便,不需要进行数据类型的强制转换,不需要使用下标!通过帮助文档的查看可知,如果要对一个对象使用foreach进行循环的话则此对象的类型必须拥有GetEnumerator方法,此方法是在IEnumerable接口下的,但是否实现此接口无所谓!GetEnumerator方法需要返回一个IEnumerator的实例,因为在进行foreach遍历时会使用到一个属性:Current和一个方法:MoveNext!以下是带有注释的源代码:
using System;
using System.Collections;
namespace ConTest01
{
 /// <summary>
 /// Class1 的摘要说明。
 /// </summary>
 class Class1
 {
  /// <summary>
  /// 应用程序的主入口点。
  /// </summary>
  [STAThread]
  static void Main(string[] args)
  {
   Persons p = new Persons("jack","tom","marry","mike");
   foreach(string s in p)
   {
    Console.WriteLine(s);
   }
  }
 }
 public class Persons
 {
  public string[] m_Names;
  public Persons(params string[] Names)
  {
   this.m_Names = new string[Names.Length];
   Names.CopyTo(this.m_Names,0);
  }
  public string this[int index]
  {
   get
   {
    return this.m_Names[index];
   }
   set
   {
    this.m_Names[index] = value;
   }
  }
  #region IEnumerable 成员
  //如果此类需要被foreach遍历则必须拥有此方法,至于是否实现IEnumerable接口倒是无所谓
  public IEnumerator GetEnumerator()
  {
   //返回一个IEnumerator的实例
   return new PersonsEnumerator(this);
  }
  #endregion
 }
 public class PersonsEnumerator : IEnumerator
 {
  private int index = -1;
  private Persons P;
  public PersonsEnumerator(Persons P)
  {
   this.P = P;
  }
  #region IEnumerator 成员
  //重置方法
  public void Reset()
  {
   this.index = -1;
  }
  //得到当前值的属性,是只读,因此在进行foreach遍历时不能修改遍历到的元素内容
  public object Current
  {
   get
   {
    return this.P[index];
   }
  }
  //将当前实例内部的索引前进一位,并判断前进后是否还有元素
  public bool MoveNext()
  {
   int tempIndex = this.index;
   if(tempIndex >= this.P.m_Names.Length)
   {
    return false;
   }
   else
   {
    return true;
   }
  }
  #endregion
 }
要对一些对象做添加修改删除处理。别的到没什么,删除时出现了点问题似的。
 
  因为是从一个类的集合中删除掉一个元素。这样就要遍历整个集合,而foreach正是为遍历准备的新玩意。自然而然用上了。于是代码类似如下:
 
string temp = name.Text; // 从TextBox中读出数据
foreach (LCourse cou in Data.myCourse) // 在List中遍历
{
if (cou.name == temp) // 判断cou的名字匹配
{
Data.myCourse.Remove(cou); // 匹配的即为要删除的,从列表中去除
break; // 跳出循环
}
}
免责声明:本站相关技术文章信息部分来自网络,目的主要是传播更多信息,如果您认为本站的某些信息侵犯了您的版权,请与我们联系,我们会即时妥善的处理,谢谢合作!