What is the real advantage of returning ICollectio

2019-04-04 11:05发布

问题:

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)?