迭代器和枚举器的区别 [英] Distinction between iterator and enumerator

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

问题描述

对于.NET 3.5的工作面试问题是一个迭代器和一个枚举器之间的区别是什么?

An interview question for a .NET 3.5 job is "What is the difference between an iterator and an enumerator"?

这是一个核心区别之作,用什么LINQ等等。

This is a core distinction to make, what with LINQ, etc.

总之,有什么区别?我似乎无法在网络上找到了坚实的定义。毫无疑问,我能找到这两个词的意思,但我得到稍微不同的答案。什么是面试的最佳答案?

Anyway, what is the difference? I can't seem to find a solid definition on the net. Make no mistake, I can find the meaning of the two terms but I get slightly different answers. What would be the best answer for an interview?

IMO迭代器迭代一个集合,和一个枚举提供迭代的功能,但是这已经被调用。

IMO an iterator "iterates" over a collection, and an enumerator provides the functionality to iterate, but this has to be called.

此外,使用屈服关键字所述保存状态。到底这是什么状态?是否有这样做的好处的发生的例子吗?

Also, using the yield keyword is said to save state. What exactly is this state? Is there an example of this benefit occurring?

推荐答案

迭代意味着重复一些步骤,同时列举手段值的集合经历的所有值。所以列举通常需要某种形式的迭代。

Iterating means repeating some steps, while enumerating means going through all values in a collection of values. So enumerating usually requires some form of iteration.

在这种方式,枚举是迭代其中的步骤是从集合中获得的值的特例。

In that way, enumerating is a special case of iterating where the step is getting a value from a collection.

请注意在一般 - 枚举也可以递归执行,但递归迭代是如此紧密,我不会在乎这点小的差异有关

Note the "usually" – enumerating may also be performed recursively, but recursion and iteration are so closely related that I would not care about this small difference.

您也可以列举你没有明确地保存在收藏价值。例如,您可以枚举的自然数,质数,或什么,但你会在枚举期间计算这些值,而不是从物理集合检索它们。你知道这种情况下枚举虚拟集合,其通过一些逻辑定义的值。

You may also enumerate values you do not explicitly store in a collection. For example, you can enumerate the natural number, primes, or whatever but you would calculate these values during the enumeration and not retrieve them from a physical collection. You understand this case as enumerating a virtual collection with its values defined by some logic.

我认为里德·科普塞了问题的实质。在C#中有两种主要方式列举的东西。

I assume Reed Copsey got the point. In C# there are two major ways to enumerate something.

  1. 实施可枚举和一个类实现的IEnumerator
  2. 执行与收益率的迭代器语句
  1. Implement Enumerable and a class implementing IEnumerator
  2. Implement an iterator with the yield statement

第一种方法是难以实现和使用对象进行枚举。第二种方法是更容易实现,并使用延续

The first way is harder to implement and uses objects for enumerating. The second way is easier to implement and uses continuations.

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

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