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

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


当前回答

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.

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

其他回答

如果您通过其他人将使用的库来公开类,则通常希望通过接口而不是具体实现来公开类。如果您决定稍后更改类的实现以使用不同的具体类,这将有所帮助。在这种情况下,库的用户不需要更新他们的代码,因为接口没有改变。

如果您只是在内部使用它,您可能不会太在意,使用List<T>可能就可以了。

如果。net 5.0取代了System.Collections.Generic。List<T>到system . collection . generic . linearlist <T>. . net总是拥有List<T>这个名称,但是他们保证IList<T>是一个契约。所以恕我直言,我们(至少我)不应该使用别人的名字(尽管在这种情况下是。net),之后会遇到麻烦。

在使用IList<T>的情况下,调用者总是保证事情正常工作,而实现者可以自由地将底层集合更改为任何可供选择的IList具体实现

List<T>是IList<T>的特定实现,它是一个容器,可以像线性数组T[]一样使用整数索引寻址。当您指定IList<T>作为方法参数的类型时,您只是指定了您需要容器的某些功能。

例如,接口规范并不强制使用特定的数据结构。List<T>的实现在访问、删除和添加元素方面与线性数组具有相同的性能。但是,您可以想象一个由链表支持的实现,其中在末尾添加元素更便宜(常量时间),但随机访问要昂贵得多。(注意。net LinkedList<T>没有实现IList<T>。)

这个例子还告诉您,在某些情况下,您可能需要在参数列表中指定实现,而不是接口:在这个例子中,当您需要特定的访问性能特征时。这通常是容器的特定实现所保证的(List<T>文档:“它使用一个数组实现IList<T>泛型接口,该数组的大小根据需要动态增加。”)。

此外,您可能需要考虑公开最少需要的功能。为例。如果你不需要改变列表的内容,你可能应该考虑使用IEnumerable<T>,它是IList<T>扩展的。

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