C# 返回 ICollection<T> 而不是 List<T> 的真正优势是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/426182/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 02:56:00  来源:igfitidea点击:

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

c#.netienumerableicollection

提问by Martin

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?

我读过几篇博客文章,提到对于公共 API,我们应该始终返回 ICollection(或 IEnumerable)而不是 List。返回 ICollection 而不是 List 的真正优势是什么?

Thanks!

谢谢!

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

重复:List (of T) 和 Collection(of T) 有什么区别?

采纳答案by Soviut

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.

简短的回答是枚举器更轻巧、更高效。

回答by ccoxtn

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.

ICollection 只是一个接口,而 List 是该接口的具体实现。如果您以后想使用除列表之外的其他容器怎么办?如果您公开公开 ICollection 接口,您可以稍后将内部容器更改为其他内容 - 只要新容器也实现 ICollection 接口。

回答by Allain Lalonde

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.

List 假定实现支持索引,但 ICollection 不做这样的假设。

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.

这意味着,如果您发现 Set 可能提供更好的性能,因为排序无关紧要,那么您可以在不影响客户的情况下自由更改您的方法。

It's basic encapsulation.

这是基本的封装。

回答by Powerlord

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

我认为 IList 会更合适,但是......