返回“IList"与“ICollection"与“Collection" [英] Returning 'IList' vs 'ICollection' vs 'Collection'

查看:33
本文介绍了返回“IList"与“ICollection"与“Collection"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对应该从公共 API 方法和属性返回哪种集合类型感到困惑.

I am confused about which collection type that I should return from my public API methods and properties.

我想到的集合是 IListICollectionCollection.

The collections that I have in mind are IList, ICollection and Collection.

返回这些类型中的一种总是比其他类型更受欢迎,还是取决于具体情况?

Is returning one of these types always preferred over the others, or does it depend on the specific situation?

推荐答案

通常,您应该返回一种尽可能通用的类型,即只知道消费者需要使用的返回数据的类型.这样您就可以更自由地更改 API 的实现,而不会破坏正在使用它的代码.

Generally you should return a type that is as general as possible, i.e. one that knows just enough of the returned data that the consumer needs to use. That way you have greater freedom to change the implementation of the API, without breaking the code that is using it.

还要考虑将 IEnumerable 接口作为返回类型.如果结果只是要迭代,消费者不需要更多.

Consider also the IEnumerable<T> interface as return type. If the result is only going to be iterated, the consumer doesn't need more than that.

这篇关于返回“IList"与“ICollection"与“Collection"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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