有人能向我解释一下为什么我想在c#中使用IList而不是List吗?

相关问题:为什么公开List<T>被认为是不好的


当前回答

通常,一个好的方法是在面向公共的API中使用IList(在适当的情况下,并且需要列表语义),然后在内部使用list来实现API。这允许您在不破坏使用您的类的代码的情况下更改到不同的IList实现。

类名List可能在下一个。net框架中改变,但接口永远不会改变,因为接口是契约。

注意,如果你的API只会在foreach循环中使用,那么你可能会考虑只暴露IEnumerable。

其他回答

所有的概念基本上都在上面关于为什么使用接口而不是具体实现的回答中说明了。

IList<T> defines those methods (not including extension methods)

IList<T> MSDN link

添加 清晰的 包含 CopyTo GetEnumerator IndexOf 插入 删除 RemoveAt

List<T>实现了这9个方法(不包括扩展方法),除此之外,它还有大约41个公共方法,这将影响您在应用程序中使用哪个方法。

List<T> MSDN link

You can look at this argument from several angles including the one of a purely OO approach which says to program against an Interface not an implementation. With this thought, using IList follows the same principal as passing around and using Interfaces that you define from scratch. I also believe in the scalability and flexibility factors provided by an Interface in general. If a class implmenting IList<T> needs to be extended or changed, the consuming code does not have to change; it knows what the IList Interface contract adheres to. However using a concrete implementation and List<T> on a class that changes, could cause the calling code to need to be changed as well. This is because a class adhering to IList<T> guarantees a certain behavior that is not guaranteed by a concrete type using List<T>.

此外,还可以在类上修改List<T>的默认实现,例如为.Add、.Remove或任何其他IList方法实现IList<T>,为开发人员提供了很大的灵活性和能力,否则由List<T>预定义

令人惊讶的是,这些List和IList的问题(或答案)都没有提到签名差异。(这就是为什么我在SO上搜索这个问题!)

下面是List中包含的在IList中找不到的方法,至少在。net 4.5(大约2015年)

AddRange AsReadOnly BinarySearch 能力 ConvertAll 存在 找到 FindAll FindIndex FindLast FindLastIndex ForEach GetRange InsertRange LastIndexOf RemoveAll RemoveRange 反向 排序 ToArray TrimExcess TrueForAll

如果您通过其他人将使用的库来公开类,则通常希望通过接口而不是具体实现来公开类。如果您决定稍后更改类的实现以使用不同的具体类,这将有所帮助。在这种情况下,库的用户不需要更新他们的代码,因为接口没有改变。

如果您只是在内部使用它,您可能不会太在意,使用List<T>可能就可以了。

List<T>是IList<T>的特定实现,它是一个容器,可以像线性数组T[]一样使用整数索引寻址。当您指定IList<T>作为方法参数的类型时,您只是指定了您需要容器的某些功能。

例如,接口规范并不强制使用特定的数据结构。List<T>的实现在访问、删除和添加元素方面与线性数组具有相同的性能。但是,您可以想象一个由链表支持的实现,其中在末尾添加元素更便宜(常量时间),但随机访问要昂贵得多。(注意。net LinkedList<T>没有实现IList<T>。)

这个例子还告诉您,在某些情况下,您可能需要在参数列表中指定实现,而不是接口:在这个例子中,当您需要特定的访问性能特征时。这通常是容器的特定实现所保证的(List<T>文档:“它使用一个数组实现IList<T>泛型接口,该数组的大小根据需要动态增加。”)。

此外,您可能需要考虑公开最少需要的功能。为例。如果你不需要改变列表的内容,你可能应该考虑使用IEnumerable<T>,它是IList<T>扩展的。