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

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


当前回答

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

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

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

其他回答

根据其他帖子的建议,IList<>几乎总是更可取的,但是请注意,在。net 3.5 sp 1中,当使用WCF DataContractSerializer运行IList<>多个序列化/反序列化周期时,有一个错误。

现在有一个SP来修复这个错误:KB 971030

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

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

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

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>预定义

TDD和OOP的一个原则通常是针对接口编程,而不是实现。

在这个特定的情况下,因为你实际上是在谈论一个语言结构,而不是一个自定义的,这通常并不重要,但比如说,你发现List不支持你需要的东西。如果你在应用的其余部分使用了IList,你可以用你自己的自定义类扩展List,并且仍然能够在不重构的情况下传递它。

这样做的成本是最小的,为什么不省去以后的麻烦呢?这就是界面原则。

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

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

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