C#中foreach實現(xiàn)原理詳解
本文主要記錄我在學習C#中foreach遍歷原理的心得體會。
對集合中的要素進行遍歷是所有編碼中經(jīng)常涉及到的操作,因此大部分編程語言都把此過程寫進了語法中,比如C#中的foreach。經(jīng)常會看到下面的遍歷代碼:
var lstStr = new List<string> { "a", "b" };
foreach (var str in lstStr)
{
Console.WriteLine(str);
}
實際此代碼的執(zhí)行過程:
var lstStr = new List<string> {"a", "b"};
IEnumerator<string> enumeratorLst = lstStr.GetEnumerator();
while (enumeratorLst.MoveNext())
{
Console.WriteLine(enumeratorLst.Current);
}
會發(fā)現(xiàn)有GetEnumerator()方法和IEnumerator<string>類型,這就涉及到可枚舉類型和枚舉器的概念。
為了方便理解,以下為非泛型示例:
// 摘要:
// 公開枚舉器,該枚舉器支持在非泛型集合上進行簡單迭代。
public interface IEnumerable
{
// 摘要:
// 返回一個循環(huán)訪問集合的枚舉器。
//
// 返回結(jié)果:
// 可用于循環(huán)訪問集合的 System.Collections.IEnumerator 對象。
IEnumerator GetEnumerator();
}
實現(xiàn)了此接口的類稱為可枚舉類型,是可以用foreach進行遍歷的標志。
方法GetEnumerator()的返回值是枚舉器,可以理解為游標。
// 摘要:
// 支持對非泛型集合的簡單迭代。
public interface IEnumerator
{
// 摘要:
// 獲取集合中的當前元素。
//
// 返回結(jié)果:
// 集合中的當前元素。
//
// 異常:
// System.InvalidOperationException:
// 枚舉數(shù)定位在該集合的第一個元素之前或最后一個元素之后。
object Current { get; }
// 摘要:
// 將枚舉數(shù)推進到集合的下一個元素。
//
// 返回結(jié)果:
// 如果枚舉數(shù)成功地推進到下一個元素,則為 true;如果枚舉數(shù)越過集合的結(jié)尾,則為 false。
//
// 異常:
// System.InvalidOperationException:
// 在創(chuàng)建了枚舉數(shù)后集合被修改了。
bool MoveNext();
//
// 摘要:
// 將枚舉數(shù)設置為其初始位置,該位置位于集合中第一個元素之前。
//
// 異常:
// System.InvalidOperationException:
// 在創(chuàng)建了枚舉數(shù)后集合被修改了。
void Reset();
}
以下是自定義一個迭代器的示例(https://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx):
using System;
using System.Collections;
// Simple business object.
public class Person
{
public Person(string fName, string lName)
{
this.firstName = fName;
this.lastName = lName;
}
public string firstName;
public string lastName;
}
// Collection of Person objects. This class
// implements IEnumerable so that it can be used
// with ForEach syntax.
public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length];
for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
}
// Implementation for the GetEnumerator method.
IEnumerator IEnumerable.GetEnumerator()
{
return (IEnumerator) GetEnumerator();
}
public PeopleEnum GetEnumerator()
{
return new PeopleEnum(_people);
}
}
// When you implement IEnumerable, you must also implement IEnumerator.
public class PeopleEnum : IEnumerator
{
public Person[] _people;
// Enumerators are positioned before the first element
// until the first MoveNext() call.
int position = -1;
public PeopleEnum(Person[] list)
{
_people = list;
}
public bool MoveNext()
{
position++;
return (position < _people.Length);
}
public void Reset()
{
position = -1;
}
object IEnumerator.Current
{
get
{
return Current;
}
}
public Person Current
{
get
{
try
{
return _people[position];
}
catch (IndexOutOfRangeException)
{
throw new InvalidOperationException();
}
}
}
}
class App
{
static void Main()
{
Person[] peopleArray = new Person[3]
{
new Person("John", "Smith"),
new Person("Jim", "Johnson"),
new Person("Sue", "Rabon"),
};
People peopleList = new People(peopleArray);
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);
}
}
/* This code produces output similar to the following:
*
* John Smith
* Jim Johnson
* Sue Rabon
*
*/
在有了yield這個關鍵字以后,我們可以通過這樣的方式來創(chuàng)建枚舉器:
using System;
using System.Collections;
// Simple business object.
public class Person
{
public Person(string fName, string lName)
{
this.firstName = fName;
this.lastName = lName;
}
public string firstName;
public string lastName;
}
// Collection of Person objects. This class
// implements IEnumerable so that it can be used
// with ForEach syntax.
public class People : IEnumerable
{
private Person[] _people;
public People(Person[] pArray)
{
_people = new Person[pArray.Length];
for (int i = 0; i < pArray.Length; i++)
{
_people[i] = pArray[i];
}
}
// Implementation for the GetEnumerator method.
IEnumerator IEnumerable.GetEnumerator()
{
for (int i = 0; i < _people.Length; i++)
{
yield return _people[i];
}
}
}
class App
{
static void Main()
{
Person[] peopleArray = new Person[3]
{
new Person("John", "Smith"),
new Person("Jim", "Johnson"),
new Person("Sue", "Rabon"),
};
People peopleList = new People(peopleArray);
foreach (Person p in peopleList)
Console.WriteLine(p.firstName + " " + p.lastName);
}
}
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持我們。
欄 目:C#教程
本文地址:http://www.jygsgssxh.com/a1/C_jiaocheng/5478.html
您可能感興趣的文章
- 01-10C#通過反射獲取當前工程中所有窗體并打開的方法
- 01-10C#實現(xiàn)txt定位指定行完整實例
- 01-10WinForm實現(xiàn)仿視頻播放器左下角滾動新聞效果的方法
- 01-10C#實現(xiàn)清空回收站的方法
- 01-10C#實現(xiàn)讀取注冊表監(jiān)控當前操作系統(tǒng)已安裝軟件變化的方法
- 01-10C#實現(xiàn)多線程下載文件的方法
- 01-10C#實現(xiàn)Winform中打開網(wǎng)頁頁面的方法
- 01-10C#實現(xiàn)遠程關閉計算機或重啟計算機的方法
- 01-10C#自定義簽名章實現(xiàn)方法
- 01-10C#文件斷點續(xù)傳實現(xiàn)方法


閱讀排行
本欄相關
- 01-10C#通過反射獲取當前工程中所有窗體并
- 01-10關于ASP網(wǎng)頁無法打開的解決方案
- 01-10WinForm限制窗體不能移到屏幕外的方法
- 01-10WinForm繪制圓角的方法
- 01-10C#實現(xiàn)txt定位指定行完整實例
- 01-10WinForm實現(xiàn)仿視頻播放器左下角滾動新
- 01-10C#停止線程的方法
- 01-10C#實現(xiàn)清空回收站的方法
- 01-10C#通過重寫Panel改變邊框顏色與寬度的
- 01-10C#實現(xiàn)讀取注冊表監(jiān)控當前操作系統(tǒng)已
隨機閱讀
- 01-10C#中split用法實例總結(jié)
- 08-05DEDE織夢data目錄下的sessions文件夾有什
- 08-05織夢dedecms什么時候用欄目交叉功能?
- 01-11Mac OSX 打開原生自帶讀寫NTFS功能(圖文
- 01-10delphi制作wav文件的方法
- 01-10使用C語言求解撲克牌的順子及n個骰子
- 04-02jquery與jsp,用jquery
- 08-05dedecms(織夢)副欄目數(shù)量限制代碼修改
- 01-10SublimeText編譯C開發(fā)環(huán)境設置
- 01-11ajax實現(xiàn)頁面的局部加載


