为什么IEnumerable< T>有IEnumerator< T>时需要吗? [英] Why is IEnumerable<T> necessary when there is IEnumerator<T>?

查看:78
本文介绍了为什么IEnumerable< T>有IEnumerator< T>时需要吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明:我了解IEnumerable<T>IEnumerator<T>之间的区别以及如何使用两者.这不是

Disclaimer: I understand the difference between IEnumerable<T> and IEnumerator<T> and how to use both. This is not a duplicate of this or this.

这更多是一个设计问题-因为IEnumerator<T>已经封装了有关所有可以枚举的必要信息(.Current.MoveNext()),那么引入类型(IEnumerable<T>)的意义何在?其唯一目的是返回前者的实例?

This is more of a design question - since IEnumerator<T> already encapsulates all the necessary information (.Current, .MoveNext()) about something that can be enumerated, then what's the point of introducing a type (IEnumerable<T>) whose sole purpose is to return an instance of the former?

要具体一点:

  1. 为什么不能将foreach设计为直接通过IEnumerator<T>进行迭代,如下所示:

  1. Why can't foreach be designed to iterate directly through an IEnumerator<T>, like so:

// foreach (var e in anEnumerator) { //... }
while (anEnumerator.MoveNext())
{
    doSomething(anEnumerator.Current);
}

  • 为什么不能直接基于IEnumerator<T>构建Linq?

  • Why can't Linq be built based directly off of IEnumerator<T>?

    推荐答案

    这两个接口各自代表了截然不同的概念. IEnumerable<T>是允许枚举"的内容,其中IEnumerator<T>是枚举本身的表示形式.

    The two interfaces each represent very different concepts. IEnumerable<T> is something that "allows enumeration", where IEnumerator<T> is the representation of the enumeration itself.

    如果将这些合并在一起,则不可能一次枚举一个集合以上(没有适当的其他机制).例如,在一个数组上执行foreach的两个线程将不再起作用,这在当前设计中是完全可以接受的.

    If you were to merge these together, it would be impossible to enumerate a single collection more than once at the same time (without some other mechanism in place). For example, two threads doing a foreach over an array would no longer work, where that is perfectly acceptable in the current design.

    这篇关于为什么IEnumerable&lt; T&gt;有IEnumerator&lt; T&gt;时需要吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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