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

查看:173
本文介绍了如何在C#中的foreach实施?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

究竟如何的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&LT; T&GT; ,只要你有它返回一个类型适用的的GetEnumerator()方法适用电流的MoveNext() 成员。正如在评论中指出,一个类型可以的的实施的IEnumerable 的IEnumerable&LT; T&GT; 明确,但它返回比其他类型公共的GetEnumerator()方法的IEnumerator / 的IEnumerator&LT ; T&GT; 。见<一href=\"http://msdn.microsoft.com/en-us/library/b0yss765.aspx\"><$c$c>List<T>.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.

这篇关于如何在C#中的foreach实施?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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