2 回答

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個(gè)贊
實(shí)際上,嚴(yán)格來(lái)說(shuō),您需要使用的foreach
只是一個(gè)使用方法和屬性GetEnumerator()
返回內(nèi)容的公共方法。但是,最常見(jiàn)的含義是“實(shí)現(xiàn)/ ,返回/的東西” 。bool MoveNext()
? Current {get;}
IEnumerable
IEnumerable<T>
IEnumerator
IEnumerator<T>
通過(guò)暗示,這包括任何實(shí)現(xiàn)ICollection
/ ICollection<T>
,如像什么Collection<T>
,List<T>
,陣列(T[]
)等。因此,任何標(biāo)準(zhǔn)的“數(shù)據(jù)集”將通常支持foreach
。
為了證明第一點(diǎn),以下工作正常:
using System;class Foo { public int Current { get; private set; } private int step; public bool MoveNext() { if (step >= 5) return false; Current = step++; return true; }}class Bar { public Foo GetEnumerator() { return new Foo(); }}static class Program { static void Main() { Bar bar = new Bar(); foreach (int item in bar) { Console.WriteLine(item); } }}
它是如何工作的?
像foreach(int i in obj) {...}
有點(diǎn)類(lèi)似的foreach循環(huán)等同于:
var tmp = obj.GetEnumerator();int i; // up to C# 4.0while(tmp.MoveNext()) { int i; // C# 5.0 i = tmp.Current; {...} // your code}
但是,有變化。例如,枚舉器(tmp)支持IDisposable
,它也被使用(類(lèi)似于using
)。
注意循環(huán)中內(nèi)部(C#5.0)與外部(上升C#4.0)的聲明“ int i
” 的位置不同。如果您在代碼塊中使用匿名方法/ lambda,這一點(diǎn)很重要。但那是另一個(gè)故事;-pi
- 2 回答
- 0 關(guān)注
- 395 瀏覽
添加回答
舉報(bào)