为什么List <t>实现了这么多接口?</t>

时间:2013-12-06 12:50:39

标签: c# derived-class

List<T>派生自以下接口:

public class List<T> : IList<T>, ICollection<T>, IEnumerable<T>, IList, ICollection, IEnumerable

我只是想知道为什么它需要所有这些接口(类声明中的 )?

IList本身已经来自ICollection<T>IEnumerable<T>IEnumerable

那么为什么以下不够呢?

public class List<T> : IList<T>, IList

我希望你能解决我的困惑。

3 个答案:

答案 0 :(得分:10)

确实List<T>会像这样实施

public class List<T> : IList<T>, IList

它是反射器或者这样的反编译器向你显示继承中的所有接口。

试试这个

public class List2<T> : IList<T>

我刚刚编译了这个并在反射器中查看,它显示如下

public class List2<T> : IList<T>, ICollection<T>, IEnumerable<T>, IEnumerable

答案 1 :(得分:2)

如果您看一下实际的.NET源代码,您会发现它并没有冗余地提及所有接口:

// Implements a variable-size List that uses an array of objects to store the
// elements. A List has a capacity, which is the allocated length 
// of the internal array. As elements are added to a List, the capacity
// of the List is automatically increased as required by reallocating the
// internal array.
// 
[DebuggerTypeProxy(typeof(Mscorlib_CollectionDebugView<>))]
[DebuggerDisplay("Count = {Count}")] 
[Serializable] 
public class List<T> : IList<T>, System.Collections.IList, IReadOnlyList<T>

反射器只列出了所有接口。

您可以获取.NET here的源代码,或快速搜索here(似乎坚持使用.NET4)。

答案 2 :(得分:1)

IMO无法推断出List<T>的实际实现是如何实际编写的。可能是:

public class List<T> : IList<T>, ICollection<T>, IList, 
                       ICollection, IReadOnlyList<T>, 
                       IReadOnlyCollection<T>, IEnumerable<T>, 
                       IEnumerable

或者它可能是一个简化版本......虽然我认为你的例子错过了ReadOnly接口,但我仍然明白这一点。

public class List<T> : IList<T>, IList

然而,就容易理解任何未来的开发人员而言(他们可能不会一直倾向于扫描继承链),我认为第一种形式可能有其好处。