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

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


当前回答

使用接口而不是实现的最重要情况是API的参数。如果API接受List参数,那么使用它的任何人都必须使用List。如果参数类型是IList,那么调用者有更多的自由,并且可以使用您从未听说过的类,这些类在编写代码时甚至可能不存在。

其他回答

public void Foo(IList<Bar> list)
{
     // Do Something with the list here.
}

在这种情况下,您可以传入任何实现了IList<Bar>接口的类。如果使用List<Bar>代替,则只能传入一个List<Bar>实例。

IList<Bar>方式比List<Bar>方式耦合更松。

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> { ... }

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

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

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

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

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