如何在C#中的foreach实施? [英] How is foreach implemented in C#?
问题描述
究竟如何的foreach
在C#中实现的?
How exactly is foreach
implemented in C#?
我想它的一部分看起来像:
I imagine a part of it looking like:
var enumerator = TInput.GetEnumerator();
while(enumerator.MoveNext())
{
// do some stuff here
}
不过我不能确定到底发生了什么的。用于返回 enumerator.Current
每个周期有什么方法?是否返回[每个周期]或没有考虑一个匿名函数或东西来执行的foreach
?
However I'm unsure what's really going on. What methodology is used for returning enumerator.Current
for each cycle? Does it return [for each cycle] or does it take an anonymous function or something to execute the body of foreach
?
推荐答案
它不使用匿名函数,没有。基本上,编译器将code弄成的大致相当于的您在此显示的while循环。
It doesn't use an anonymous function, no. Basically the compiler converts the code into something broadly equivalent to the while loop you've shown here.
的foreach
的不的函数调用 - 它的内置到语言本身,就像为
循环和,而
循环。有没有必要为它返回任何东西,或吃任何类型的功能。
foreach
isn't a function call - it's built-into the language itself, just like for
loops and while
loops. There's no need for it to return anything or "take" a function of any kind.
注意的foreach
有一些有趣的皱纹:
Note that foreach
has a few interesting wrinkles:
- 当遍历数组(在编译时已知)的编译器可以使用循环计数器和数组,而不是使用的长度比较的
的IEnumerator
-
的foreach
将部署在最后的迭代器;这是简单的的IEnumerator< T>
延伸的IDisposable
,但作为的IEnumerator
的不的,编译器插入检查在执行时测试是否迭代器工具的IDisposable
- 您可以在不实现类型的迭代
的IEnumerable
或的IEnumerable< T>
,只要你有它返回一个类型适用的的GetEnumerator()
方法适用电流
和的MoveNext()
成员。正如在评论中指出,一个类型可以的也的实施的IEnumerable
或的IEnumerable< T>
明确,但它返回比其他类型公共的GetEnumerator()
方法的IEnumerator
/的IEnumerator&LT ; T>
。见<一href=\"http://msdn.microsoft.com/en-us/library/b0yss765.aspx\"><$c$c>List<T>.GetEnumerator()$c$c>对于一个例子 - 这避免了在许多情况下不必要创建引用类型的对象 。
- When iterating over an array (known at compile-time) the compiler can use a loop counter and compare with the length of the array instead of using an
IEnumerator
foreach
will dispose of the iterator at the end; that's simple forIEnumerator<T>
which extendsIDisposable
, but asIEnumerator
doesn't, the compiler inserts a check to test at execution time whether the iterator implementsIDisposable
- You can iterate over types which don't implement
IEnumerable
orIEnumerable<T>
, so long as you have an applicableGetEnumerator()
method which returns a type with suitableCurrent
andMoveNext()
members. As noted in comments, a type can also implementIEnumerable
orIEnumerable<T>
explicitly, but have a publicGetEnumerator()
method which returns a type other thanIEnumerator
/IEnumerator<T>
. SeeList<T>.GetEnumerator()
for an example - this avoids creating a reference type object unnecessarily in many cases.
查看C#4规范第8.8.4以获取更多信息。
See section 8.8.4 of the C# 4 spec for more information.
这篇关于如何在C#中的foreach实施?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!