我应该使用IEnumerable还是IList? [英] What should I use an IEnumerable or IList?

查看:144
本文介绍了我应该使用IEnumerable还是IList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我什么时候使用.

Can anyone tell me when I should use either.

例如,我想访问集合的.Count或单个项目时应该使用IList,对吗?

For example, I think I should use an IList when I want to access the .Count of the collection or an individual item, correct?

谢谢.

推荐答案

通常来说,您应该尝试使用适合您目的的最不特定的类型. IEnumerable的定义不如IList(IList实现IEnumerable)明确,因此除非您想要IList中的特定内容(例如您建议的Count,或者AddDelete等), ),我会使用IEnumerable.

Generally speaking, you should try and use the least specific type that suits your purpose. IEnumerable is less specific than IList (IList implements IEnumerable) so unless you want something specific from IList (such as Count as you suggest, or perhaps Add, Delete, etc), I'd use IEnumerable.

使用IEnumerable保留的一个好处是,您可以编写迭代器方法以返回此类型(如果您不熟悉它们,请查找"yield return"和迭代器方法).这使您可以为循环编写内存效率很高的管道".

One benefit of remaining with IEnumerable is that you can write iterator methods to return this type (look up "yield return" and iterator methods if you are not familiar with them). This allows you to write very memory efficient "pipelines" for your loops.

这篇关于我应该使用IEnumerable还是IList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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