C# foreach循環實例詳解

在編寫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; // 跳出循環
}
}

發佈了1 篇原創文章 · 獲贊 3 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章