foreach是如何在C#中实现的? [英] How is foreach implemented in C#?

查看:29
本文介绍了foreach是如何在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 会在最后处理迭代器;这对于扩展 IDisposableIEnumerator 来说很简单,但是作为 IEnumerator ,编译器插入了一个在执行时检查迭代器是否实现了IDisposable
  • 您可以迭代未实现 IEnumerableIEnumerable 的类型,只要您有适用的 GetEnumerator()> 方法返回具有合适的 CurrentMoveNext() 成员的类型.如注释中所述,类型可以显式实现 IEnumerableIEnumerable,但具有公共 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 for IEnumerator<T> which extends IDisposable, but as IEnumerator doesn't, the compiler inserts a check to test at execution time whether the iterator implements IDisposable
  • You can iterate over types which don't implement IEnumerable or IEnumerable<T>, so long as you have an applicable GetEnumerator() method which returns a type with suitable Current and MoveNext() members. As noted in comments, a type can also implement IEnumerable or IEnumerable<T> explicitly, but have a public GetEnumerator() method which returns a type other than IEnumerator/IEnumerator<T>. See List<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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆