什么是返回的ICollection&LT的真正优势; T> ;? T>而不是一个名单,其中是一个、而不、优势、名单

2023-09-03 05:54:33 作者:無情便是王

我读了几个博客中提到,对于公共API,我们应该始终返回,而不是名单的ICollection(或IEnumerable的)。什么是返回一个列表的ICollection,而不是真正的优势在哪里?

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?

谢谢!

复制:What是列表(的T)和集合(T)的?

推荐答案

这是枚举器仅返回一次一个实体,你遍历它。这是因为它使用了收益率回归。集合,在另一方面,返回整个列表,要求该列表被完全存储在存储器

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.