foreach是如何在C#中实现的? [英] 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
?它是返回 [for each cycle] 还是需要匿名函数或其他东西来执行 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
?
推荐答案
它不使用匿名函数,不.基本上,编译器将代码转换为大致等效的内容,与您在此处显示的 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
不是函数调用 - 它是内置于语言本身的,就像 for
循环和 while
循环.它不需要返回任何东西或获取"任何类型的函数.
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
会在最后处理迭代器;这对于扩展IDisposable
的IEnumerator
来说很简单,但是作为IEnumerator
不,编译器插入了一个在执行时检查迭代器是否实现了IDisposable
- 您可以迭代未实现
IEnumerable
或IEnumerable
的类型,只要您有适用的GetEnumerator()
> 方法返回具有合适的Current
和MoveNext()
成员的类型.如注释中所述,类型可以也显式实现IEnumerable
或IEnumerable
,但具有公共GetEnumerator()
方法返回的类型不是IEnumerator
/IEnumerator
.请参阅List
例如 - 这避免了在许多情况下不必要地创建引用类型对象..GetEnumerator()
- 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.
这篇关于foreach是如何在C#中实现的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!