解释为什么IEnumerable比List更有效 [英] Explanation why IEnumerable is more efficient than a List

查看:234
本文介绍了解释为什么IEnumerable比List更有效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在听说,在.net 3.5中,您应该在列表上使用IEnumerable,但是我找不到任何参考资料或文章来解释为什么它如此精通。有人知道任何解释此内容的内容吗?

I keep hearing that in .net 3.5 you should use IEnumerable over a List, but I can’t find any reference materials or articles that explain why it’s so much more proficient. Does anyone know of any content that explains this?

问这个问题的目的是为了更好地了解IEnumerable在幕后所做的事情。如果您可以提供任何链接,我将进行研究并发布答案。

The purpose of asking this question is to get a better understanding of what IEnumerable is doing under the hood. If you can provide me with any links I will do the research and post an answer.

推荐答案

IEnumerable< T> 的接口由 List< T> 实现。我怀疑您听到应该使用 IEnumerable< T> 的原因是因为它对接口的要求不那么严格。

IEnumerable<T> is an interface that is implemented by List<T>. I suspect the reason you're hearing that IEnumerable<T> should be used is because it's a less constrictive interface requirement.

例如,考虑以下方法签名:

For example, consider the following method signature:

void Output(List<Foo> foos) 
{ 
    foreach(var foo in foos) { /* do something */ }
}

此方法要求将其传递给List的具体实现。但这只是在按顺序进行。它实际上并不需要随机访问或 List< T> 或什至 IList< T> 给它。相反,该方法应接受 IEnumerable< T>

This method requires that it be passed a concrete implementation of a List. But it's just doing something in-order. It doesn't really need random access or any of the other things that a List<T> or even an IList<T> give it. Instead, the method should accept an IEnumerable<T>:

void Output(IEnumerable<Foo> foos) 
{ 
    foreach(var foo in foos) { /* do something */ }
}

现在,我们正在使用支持所需操作的最通用(最不特定)的界面。这是面向对象设计的基本方面。我们只需要我们所需的东西,而不是其他很多东西,从而减少了耦合。我们还创建了一个更灵活的 方法,因为 foos 参数可能是 Queue< T> 列表< T> 任何实现 IEnumerable< T> 的东西。我们不会强迫调用者不必要地将其数据结构转换为List。

Now we're using the most general (least specific) interface that supports the operations that we need. This is a fundamental aspect of OO-design. We've decreased coupling by requiring only what we need, and not a whole lot else besides. We've also created a more flexible method because the foos parameter might be a Queue<T>, a List<T>, anything that implements IEnumerable<T>. We aren't forcing the caller to convert their data structure to a List unnecessarily.

所以不是 IEnumerable< T> code>比性能或运行时方面的列表更有效。因为 IEnumerable< T> 是一种更有效的 design 构造,因为它可以更具体地表明您的设计要求。 (尽管这可以在特定情况下带来运行时收益。)

So it isn't that IEnumerable<T> is more efficient than list in a "performance" or "runtime" aspect. It's that IEnumerable<T> is a more efficient design construct because it's a more specific indication of what your design requires. (Though this can lead to runtime gains in specific cases.)

这篇关于解释为什么IEnumerable比List更有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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