What is the real advantage of returning ICollection<T> instead of a List<T>? [duplicate]

北城以北 提交于 2019-12-12 08:20:04

问题


I've read a couple of blog post mentioning that for public APIs we should always return ICollection (or IEnumerable) instead of List. What is the real advantage of returning ICollection instead of a List?

Thanks!

Duplicate: What is the difference between List (of T) and Collection(of T)?


回答1:


An enumerator only returns one entity at a time as you iterate over it. This is because it uses a yield return. A collection, on the other hand, returns the entire list, requiring that the list be stored completely in memory.

The short answer is that enumerators are lighter and more efficient.




回答2:


It gives you more freedom when choosing the Underlying data structure.

A List assumes that the implementation supports indexing, but ICollection makes no such assumption.

This means that if you discover that a Set might provide better performance since ordering is irrelevant, then you're free to change your approach without affecting clients.

It's basic encapsulation.




回答3:


I would think IList would be more appropriate, but...




回答4:


ICollection is just an interface, while List is a specific implementation of that interface. What if you wanted to later on use some other container besides a list? If you publicly expose an ICollection interface, you can change your internal container to something else later on - as long as the new container also implements the ICollection interface.




回答5:


See What is the difference between List (of T) and Collection(of T)?



来源:https://stackoverflow.com/questions/426182/what-is-the-real-advantage-of-returning-icollectiont-instead-of-a-listt

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!