解释为什么IEnumerable的是更有效的再一个列表 [英] Explanation why IEnumerable is more efficient then a List

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

问题描述

我不断听到,在.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> 执行的通过接口名单,其中,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 */ }
}

此方法需要,它可以通过一个具体的实施名单。但它只是做一些有序。它并不真正需要随机访问或任何其他的东西,一个名单,其中,T&GT; 甚至是的IList&LT; T&GT; 给它。相反,该​​方法应该接受一个的IEnumerable&LT; T&GT;

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 参数可能是一个问答LT; T&GT; ,一个名单,其中,T&GT; 什么的实现的IEnumerable&LT; T&GT; 。我们不会强迫呼叫者的数据结构转换成一个列表不必要的。

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&LT; T&GT; 比列表中的表现或运行方面更有效率。这是的IEnumerable&LT; T&GT; 是一种更有效的设计的构造,因为它是一个什么样的设计需要更具体的指示。 (尽管这可能导致运行时的收益在特定情况下。)

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的是更有效的再一个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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