列表,IList的和IEnumerable的比较 [英] Comparison between List, IList and IEnumerable

查看:163
本文介绍了列表,IList的和IEnumerable的比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#应用程序中,我处理一些集合类型。我需要知道这些类型之间的差异:

i have a C# application in which i handle some collections type. I need to know what the differences between these types:

  1. <一个href="http://msdn.microsoft.com/en-us/library/6sh2ey19%28v=vs.110%29.aspx"><$c$c>List
  2. <一个href="http://msdn.microsoft.com/en-us/library/system.collections.ilist%28v=vs.110%29.aspx"><$c$c>IList
  3. <一个href="http://msdn.microsoft.com/en-us/library/system.collections.ienumerable%28v=vs.110%29.aspx"><$c$c>IEnumerable

有什么优势为每一个与别人比较呢?

What are the advantages for each one in comparison with the others?

推荐答案

  • 的IEnumerable&LT; T&GT; 是基本接口,下面的扩展或实现。它不允许直接访问和是只读的。因此,使用这个唯一的,如果你打算遍历集合。

  • IEnumerable<T> is the base interface that the following extend or implement. It doesn't allow for direct access and is readonly. So use this only if you intend to iterate over the collection.

    的ICollection&LT; T&GT; 扩展的IEnumerable&LT; T&GT; 但是除了允许添加,删除,测试一个元素是否为present集合中和得到的元素的总数。它不允许用于通过索引直接访问的元素。因为你需要开始进行迭代,直到你找到相应的元素,这将是一个O(n)的操作。

    ICollection<T> extendsIEnumerable<T> but in addition allows for adding, removing, testing whether an element is present in the collection and getting the total number of elements. It doesn't allow for directly accessing an element by index. That would be an O(n) operation as you need to start iterating over it until you find the corresponding element.

    的IList&LT; T&GT; 扩展的ICollection&LT; T&GT; (因此它继承了它的所有属性)但除了允许通过索引直接访问元素。这是一个O(1)操作。

    IList<T> extends ICollection<T> (and thus it inherits all its properties) but in addition allows for directly accessing elements by index. It's an O(1) operation.

    名单,其中,T&GT; 只是一个具体的实施的IList&LT的; T&GT; 接口

    List<T> is just a concrete implementation of the IList<T> interface.

    在你的code,你应该总是暴露出最高的,将对应于呼叫者的需求对象层次中的类型。因此,例如,如果主叫方只打算枚举数据集,使用的IEnumerable&LT; T&GT; 。如果他们需要通过索引直接访问元素暴露一个的IList&LT; T&GT;

    In your code you should always expose the type that's highest in the object hierarchy that will correspond to the needs of the callers. So for example if the callers are only going to enumerate over the dataset, use IEnumerable<T>. If they need to have direct access to elements by index expose an IList<T>.

    名单,其中,T&GT; 应该只在内部使用的code,但通常不是present在你揭露的方法的签名。这给了你更多的灵活性,你可以很容易地交换的具体实施,而不会破坏合同。

    List<T> should only be used internally by your code but usually not present in the signature of the methods you are exposing. This gives you more flexibility as you could easily swap the concrete implementation without breaking the contract.

    这篇关于列表,IList的和IEnumerable的比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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