为什么要返回一个集合接口而不是一个具体的类型?是一个、而不、接口、具体

2023-09-03 12:23:22 作者:青衫寒月千裳烬

我注意到在别人的code表示方法返回泛型集合将几乎总是返回一个接口(例如的IEnumerable< T> 的IList< T> ),而不是一个具体的实施

I've noticed in other people's code that methods returning generic collections will almost always return an interface (e.g. IEnumerable<T> or IList<T>) rather than a concrete implementation.

我有两个相关的问题。首先,为什么(如果有的话)被其认为是更好的返回一个接口?其次,有没有包括排序方法的集合接口(如名单,其中,T&GT; 呢)?

I have two related questions. Firstly, why (if at all) is it considered better to return an interface? Secondly, is there a collection interface that includes the Sort method (as List<T> does)?

推荐答案

从 C# - 列表或IList的

如果您通过暴露你的类   其他人会使用,您的库   一般想通过揭露它   接口而不是具体的   实现。如果这将有助于   决定改变实施   类后使用不同   具体类。在这种情况下   用户库的不需要   由于接口更新自己的code   不改变

If you are exposing your class through a library that others will use, you generally want to expose it via interfaces rather than concrete implementations. This will help if you decide to change the implementation of your class later to use a different concrete class. In that case the user's of your library won't need to update their code since the interface doesn't change.

如果你只是使用它的内部,   你可能顾不了那么多,并且使用   列表可能是好的。

If you are just using it internally, you may not care so much, and using List may be ok.