List,IList和IEnumerable之间的比较 [英] Comparison between List, IList, and IEnumerable

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

问题描述

我有一个处理某些集合类型的C#应用​​程序。我需要知道这些类型之间的区别是什么:

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


  1. 列表

  2. IList

  3. IEnumerable

  1. List
  2. IList
  3. IEnumerable

每个人与其他人相比有什么区别?

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

推荐答案


  • IEnumerable< T> 是以下扩展或实现的基本接口。它不允许直接访问,并且是只读的。因此,仅当您打算遍历集合时才使用此方法。

    • 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< T> extends IEnumerable< T> ,但是另外还允许添加,删除,测试元素是否存在于集合中并获取元素总数。不允许直接按索引访问元素。这将是一个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< T> 扩展了 ICollection< T> (因此它继承了其所有属性),但另外还允许通过索引直接访问元素。这是一个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.

      List< T> 只是该对象的具体实现 IList< T> 界面。

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

      在您的代码中应始终公开对象层次结构中与调用者需求相对应的最高类型。因此,例如,如果调用方仅要枚举数据集,请使用 IEnumerable< T> 。如果他们需要通过索引直接访问元素,则公开一个 IList< T>

      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>.

      List< T> 仅应在代码内部使用,而通常不出现在方法签名中你正在暴露。这样可以为您提供更大的灵活性,因为您可以轻松地交换具体的实现而无需违反合同。

      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.

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

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