为什么会出现两种完全不同的目录和IEnumerable版本反向的? [英] Why there is two completely different version of Reverse for List and IEnumerable?

查看:140
本文介绍了为什么会出现两种完全不同的目录和IEnumerable版本反向的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于列表对象,我们有一个叫做的反向()。结果
它反'到位'的名单,它不返回任何东西的顺序。

For the List object, we have a method called Reverse().
It reverse the order of the list 'in place', it doesn't return anything.

对于的IEnumerable 对象,我们有一个叫做的反向()。结果
它返回另一个IEnumerable的。

For the IEnumerable object, we have an extension method called Reverse().
It returns another IEnumerable.

我需要以相反的顺序throught列表进行迭代,这样我就可以。'T直接使用第二种方法,因为我得到一个名单,我不想要扭转它,只是向后遍历

I need to iterate in reverse order throught a list, so I can't directly use the second method, because I get a List, and I don't want to reverse it, just iterate backwards.

所以,我可以这样做:

So I can either do this :

for(int i = list.Count - 1; i >=0; i--)

foreach(var item in list.AsEnumerable().Reverse())

我发现它比如果不可读我有一个IEnumerable,只是做

I found it less readable than if I have an IEnumerable, just do

foreach(var item in list.Reverse())

我不明白为什么这2种方法已经实施这种方式,具有相同的名称。这是很烦人和混乱。

I can't understand why this 2 methods have been implemented this way, with the same name. It is pretty annoying and confusing.

为什么没有),对所有的IEnumerable

Why there is not an extension called BackwardsIterator() in the place of Reverse() working for all IEnumerable?

我对这个选择的历史原因非常感兴趣,比'怎么做'的东西多!

I'm very interested by the historical reason of this choice, more than the 'how to do it' stuff!

推荐答案

值得注意的是,该清单方法比扩展方法大很多。命名很可能保持不变为反向似乎比 BackwardsIterator 更加简洁。

It is worth noting that the list method is a lot older than the extension method. The naming was likely kept the same as Reverse seems more succinct than BackwardsIterator.

如果你想绕过列表版本,并转到扩展方法,你需要把列表像的IEnumerable< T>

If you want to bypass the list version and go to the extension method, you need to treat the list like an IEnumerable<T>:

var numbers = new List<int>();
numbers.Reverse(); // hits list
(numbers as IEnumerable<int>).Reverse(); // hits extension

或致电扩展方法为静态方法:

Or call the extension method as a static method:

Enumerable.Reverse(numbers);



请注意,可枚举版本将需要遍历枚举底层完全以开始反向迭代它。如果您打算在同一枚举此多次这样做,可以考虑永久扭转秩序和正常迭代它。

Note that the Enumerable version will need to iterate the underlying enumerable entirely in order to start iterating it in reverse. If you plan on doing this multiple times over the same enumerable, consider permanently reversing the order and iterating it normally.

这篇关于为什么会出现两种完全不同的目录和IEnumerable版本反向的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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