为什么List<T>要实现这么多接口?

8

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

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


2
你在哪里看到它是从所有这些接口派生而来的?可能只是你正在使用的工具扩展了IList<T>的实现者/派生类/任何更好的描述符。 - StingyJack
8
List<T>只继承自System.Object,但它实现了许多接口。 - Lukazoid
10
“因为它实现了许多功能”这个论点完全忽略了问题的要点。 - spender
5
我不喜欢这些关闭投票。我不认为原帖询问任何人的意见。我认为他在问“为什么”是以那种方式实现的。 - Soner Gönül
1
这个观点基于什么?OP明显在问为什么有一个(看似)多余的部分。 - gwiazdorrr
显示剩余4条评论
3个回答

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

我使用了Visual Studio 2012的类型定义和MSDN文档。 - Andy
2
@Andy 我猜 MSDN 文档会展开层次结构,这样你就不必查找所有继承的接口了。 - Matthew Watson
可能只是为了您的参考和完整性而显示。您不必列出所有这些。 - StingyJack

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的源代码(链接),或者在此处进行快速搜索(链接)(似乎仅适用于.NET4)。


2
你发的第二个链接对代码做了一些非常恶心的事情。在文档中搜索 <T>,你就会知道我在说什么了。 - spender
@spender 嗯,我也看到了 - 这绝对是 List<T> 的源代码,但 HTML 格式化已经剥离了所有的 <>。此外,如果你去它的主页 (http://www.dotnetframework.org/Search.aspx) 并搜索 List<T>,它会 真的 失控。 :) - Matthew Watson
@spender:嗯,我能说什么……在我的机器上运行™。 - gwiazdorrr

1

我认为不可能推断出 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

然而,就易于理解性而言,对于任何未来的开发人员(可能不倾向于扫描整个继承链),我认为第一种形式可能有其优势。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接