有人能向我解释一下为什么我想在c#中使用IList而不是List吗?
相关问题:为什么公开List<T>被认为是不好的
有人能向我解释一下为什么我想在c#中使用IList而不是List吗?
相关问题:为什么公开List<T>被认为是不好的
当前回答
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>预定义
其他回答
使用接口而不是实现的最重要情况是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>方式耦合更松。
TDD和OOP的一个原则通常是针对接口编程,而不是实现。
在这个特定的情况下,因为你实际上是在谈论一个语言结构,而不是一个自定义的,这通常并不重要,但比如说,你发现List不支持你需要的东西。如果你在应用的其余部分使用了IList,你可以用你自己的自定义类扩展List,并且仍然能够在不重构的情况下传递它。
这样做的成本是最小的,为什么不省去以后的麻烦呢?这就是界面原则。
如果。net 5.0取代了System.Collections.Generic。List<T>到system . collection . generic . linearlist <T>. . net总是拥有List<T>这个名称,但是他们保证IList<T>是一个契约。所以恕我直言,我们(至少我)不应该使用别人的名字(尽管在这种情况下是。net),之后会遇到麻烦。
在使用IList<T>的情况下,调用者总是保证事情正常工作,而实现者可以自由地将底层集合更改为任何可供选择的IList具体实现
如果您通过其他人将使用的库来公开类,则通常希望通过接口而不是具体实现来公开类。如果您决定稍后更改类的实现以使用不同的具体类,这将有所帮助。在这种情况下,库的用户不需要更新他们的代码,因为接口没有改变。
如果您只是在内部使用它,您可能不会太在意,使用List<T>可能就可以了。