IList的VS ICollection的VS系列系列、IList、VS、ICollection

2023-09-02 12:01:05 作者:余生太长你太难忘

我只是困惑保持输出类型,我的公开API的方法。你能告诉我为什么,哪些类型,我应该在这些使用:IList的VS ICollection的VS系列的方法我的返回类型

I was just confused for keeping the output type for my public API methods. Can you tell me why and which Type should I use among these: IList vs ICollection vs Collection for my return type of methods?

推荐答案

通常你应该返回一个类型,是尽可能地通用,即一个知道刚够返回的数据,消费者需要使用。这样,你有更多的自由来改变API的实现,而不会破坏正在使用它的code。

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< T> 接口返回类型。如果结果只会迭代,消费者不需要更多了。

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.