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

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


当前回答

因为定义IList或ICollection将为接口的其他实现打开空间。

您可能希望有一个IOrderRepository,它在IList或ICollection中定义一个订单集合。然后,您可以使用不同类型的实现来提供订单列表,只要它们符合IList或ICollection定义的“规则”。

其他回答

令人惊讶的是,这些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

因为定义IList或ICollection将为接口的其他实现打开空间。

您可能希望有一个IOrderRepository,它在IList或ICollection中定义一个订单集合。然后,您可以使用不同类型的实现来提供订单列表,只要它们符合IList或ICollection定义的“规则”。

The interface ensures that you at least get the methods you are expecting; being aware of the definition of the interface ie. all abstract methods that are there to be implemented by any class inheriting the interface. so if some one makes a huge class of his own with several methods besides the ones he inherited from the interface for some addition functionality, and those are of no use to you, its better to use a reference to a subclass (in this case the interface) and assign the concrete class object to it.

额外的好处是,你的代码是安全的,不受任何对具体类的更改,因为你只订阅了具体类的几个方法,而这些方法是那些只要具体类继承了你正在使用的接口就会存在的方法。所以这对你来说是安全的,对编写具体实现的编码器来说是自由的,他可以改变或添加更多的功能到他的具体类中。

IList<T>是一个接口,所以你可以继承另一个类,仍然实现IList<T>,而继承List<T>阻止你这样做。

例如,如果有一个类a,你的类B继承了它,那么你不能使用List<T>

class A : B, IList<T> { ... }

我将把这个问题稍微转一下,与其证明为什么应该使用接口而不是具体实现,不如尝试证明为什么应该使用具体实现而不是接口。如果你不能证明这一点,那就使用界面。