有人能向我解释一下为什么我想在c#中使用IList而不是List吗?
相关问题:为什么公开List<T>被认为是不好的
有人能向我解释一下为什么我想在c#中使用IList而不是List吗?
相关问题:为什么公开List<T>被认为是不好的
当前回答
我将把这个问题稍微转一下,与其证明为什么应该使用接口而不是具体实现,不如尝试证明为什么应该使用具体实现而不是接口。如果你不能证明这一点,那就使用界面。
其他回答
不太流行的答案是,程序员喜欢假装他们的软件在世界各地都可以重用,而事实上,大多数项目将由少数人维护,无论界面相关的声音有多好,你都在欺骗自己。
架构宇航员。你编写自己的IList,为。net框架中已经存在的IList添加任何东西的机会是如此渺茫,以至于它只是理论上的“最佳实践”。
很明显,如果你被问到在面试中使用什么,你会说IList,微笑,两个人看起来都为自己的聪明感到高兴。或者对于一个面向公众的API, IList。希望你明白我的意思。
根据其他帖子的建议,IList<>几乎总是更可取的,但是请注意,在。net 3.5 sp 1中,当使用WCF DataContractSerializer运行IList<>多个序列化/反序列化周期时,有一个错误。
现在有一个SP来修复这个错误:KB 971030
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