Foreach循环和枚举器之间的区别..?!? [英] Difference between Foreach loop and enumerator..?!?

查看:110
本文介绍了Foreach循环和枚举器之间的区别..?!?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我是新手程序员



我只是想知道 Foreach循环和枚举器之间的区别。



我的困惑在于此。



两个代码都提供相同的输出,但为什么枚举器优先于某些程序中的 foreach 循环...?

Hi all,

I''m a newbie programmer

I just wanted to know the difference between Foreach loop and enumerator.

My confusion lies in here.

Both the codes give same output but why enumerator is preferred over foreach loop in some programs...?!

推荐答案

foreach is只是一个快捷方式,简化了执行集合枚举的过程。来自 http://support.microsoft.com/kb/307484 [ ^ ],描述如何创建自定义集合(实现IEnumerable):



这是如何工作的? For Each调用GetEnumerator方法创建Enumerator对象,并调用MoveNext方法将光标设置为第一个项目。然后访问Current属性以获取MyObj中的项目。重复此操作,直到MoveNext返回False。



换句话说,您的集合实现了IEnumerable接口,这需要一个GetEnumerator方法。这个GetEnumerator方法返回一个知道如何进行实际枚举的IEnumerator,遍历你的集合。
foreach is just a shortcut, that simplifies performing the collection enumeration. From http://support.microsoft.com/kb/307484[^], which describes how to create a custom collection (implementing IEnumerable):

How does this work? For Each calls the GetEnumerator method to create the Enumerator object and calls the MoveNext method to set the cursor to the first item. Then the Current property is accessed to get the item in MyObj. This is repeated until MoveNext returns False.

In other words, your collection implements the IEnumerable interface, which requires a GetEnumerator method. This GetEnumerator method returns an IEnumerator that knows how to do the actual enumeration, traversing your collection.


No。这些东西是互补的。枚举器(和枚举符)可用于从不可索引的或非预填充的集合中逐个获取元素。 foreach 是可以用来遍历这些集合的循环。您不能使用for循环,因为您不能依赖索引。但是,您可以使用实现的接口公开的方法使用一些while循环 - 但是foreach要简单得多。
No. These things are complementary. Enumerators (and enumerables) can be used to get elements one by one from a non-indexable, or not pre-filled set. The foreach is the kind of loop you can use to traverse these sets. You can not use for loops since you can not rely on indexes. You could however user the methods exposed by the implemented interfaces an some while loop - but foreach is much more simpler.


这篇关于Foreach循环和枚举器之间的区别..?!?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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