3 回答

TA貢獻(xiàn)1725條經(jīng)驗(yàn) 獲得超8個(gè)贊
一個(gè)for循環(huán)被編譯的代碼大約相當(dāng)于這個(gè):
int tempCount = 0;
while (tempCount < list.Count)
{
if (list[tempCount].value == value)
{
// Do something
}
tempCount++;
}
其中,將foreach循環(huán)編譯為大致等效于此的代碼:
using (IEnumerator<T> e = list.GetEnumerator())
{
while (e.MoveNext())
{
T o = (MyClass)e.Current;
if (row.value == value)
{
// Do something
}
}
}
正如您所看到的,這都取決于枚舉器的實(shí)現(xiàn)方式以及列表索引器的實(shí)現(xiàn)方式。事實(shí)證明,基于數(shù)組的類型的枚舉數(shù)通常是這樣寫的:
private static IEnumerable<T> MyEnum(List<T> list)
{
for (int i = 0; i < list.Count; i++)
{
yield return list[i];
}
}
正如您所看到的,在這種情況下,它并沒有太大的區(qū)別,但是鏈表的枚舉數(shù)可能看起來像這樣:
private static IEnumerable<T> MyEnum(LinkedList<T> list)
{
LinkedListNode<T> current = list.First;
do
{
yield return current.Value;
current = current.Next;
}
while (current != null);
}
在.NET中,您會(huì)發(fā)現(xiàn)LinkedList <T>類甚至沒有索引器,因此您將無法在鏈表上進(jìn)行for循環(huán);但是如果可以的話,索引器的編寫必須像這樣:
public T this[int index]
{
LinkedListNode<T> current = this.First;
for (int i = 1; i <= index; i++)
{
current = current.Next;
}
return current.value;
}
如您所見,在循環(huán)中多次調(diào)用此方法要比使用可以記住它在列表中位置的枚舉器慢得多。
- 3 回答
- 0 關(guān)注
- 835 瀏覽
添加回答
舉報(bào)