所有数组在C#中实现了哪些接口?

ET.*_*ET. 67 .net c# arrays interface-implementation

作为一名新的.NET 3.5程序员,我开始学习LINQ,我发现了一些非常基本的东西,我之前没有注意到:

本书声称每个数组实现IEnumerable<T>(显然,否则我们不能使用LINQ到数组上的对象......).当我看到这个时,我心里想,我从未真正想过这个,我问自己所有数组实现了什么 - 所以我检查了 System.Array使用对象浏览器(因为它是CLR中每个数组的基类),并且我很惊讶,它没有实现IEnumerable<T>.

所以我的问题是:定义在哪里?我的意思是,我怎么能准确地告诉每个阵列实现哪些接口?

Bol*_*ock 70

文档(强调我的):

[...] Array类实现System.Collections.Generic.IList<T>,System.Collections.Generic.ICollection<T>以及System.Collections.Generic.IEnumerable<T>通用接口.这些实现在运行时提供给数组,因此文档构建工具不可见.

编辑:正如Jb Evain在他的评论中指出的那样,只有向量(一维数组)实现了通用接口.至于为什么多维数组不实现泛型接口,我不太确定,因为它们确实实现了非泛型对应(参见下面的类声明).

System.Array类(即阵列)也实现了这些非通用接口:

public abstract class Array : ICloneable, IList, ICollection, IEnumerable, IStructuralComparable, IStructuralEquatable
Run Code Online (Sandbox Code Playgroud)

  • 我没有downvote,但只有vector(一维数组)类型实现了泛型接口.多维数组类型不实现它们. (5认同)
  • 我会说:继承这个非泛型类,从而实现这些非泛型接口 (3认同)
  • @Hosam Aly:锯齿状数组只不过是碰巧包含其他向量的向量.所以这里并不奇怪. (3认同)

Hos*_*Aly 65

您可以使用小代码片段凭经验找到问题的答案:

foreach (var type in (new int[0]).GetType().GetInterfaces())
    Console.WriteLine(type);
Run Code Online (Sandbox Code Playgroud)

运行上面的代码段将导致以下输出(在.NET 4.0上):

System.ICloneable
System.Collections.IList
System.Collections.ICollection
System.Collections.IEnumerable
System.Collections.IStructuralComparable
System.Collections.IStructuralEquatable
System.Collections.Generic.IList`1[System.Int32]
System.Collections.Generic.ICollection`1[System.Int32]
System.Collections.Generic.IEnumerable`1[System.Int32]
Run Code Online (Sandbox Code Playgroud)

(.NET 4.0意思是`1)

  • @Thomas:谢谢你的建议.我更喜欢使用`(new int [0]).GetType()`来确保结果包含在运行时*提供给数组的任何*实现,如@BoltClock所述. (14认同)
  • +1,虽然我会使用`typeof(int [])`而不是`(new int [0] .GetType()`... (9认同)

cr7*_*ph7 54

.NET 4.5开始,数组也实现了接口System.Collections.Generic.IReadOnlyList<T>System.Collections.Generic.IReadOnlyCollection<T>.

因此,当使用.NET 4.5时,由数组实现的完整接口列表变为(使用Hosam Aly的答案中提供的方法获得):

System.Collections.IList
System.Collections.ICollection
System.Collections.IEnumerable
System.Collections.IStructuralComparable
System.Collections.IStructuralEquatable
System.Collections.Generic.IList`1[System.Int32]
System.Collections.Generic.ICollection`1[System.Int32]
System.Collections.Generic.IEnumerable`1[System.Int32]
System.Collections.Generic.IReadOnlyList`1[System.Int32]
System.Collections.Generic.IReadOnlyCollection`1[System.Int32]
Run Code Online (Sandbox Code Playgroud)

奇怪的是,似乎忘记更新MSDN上的文档以提及这两个接口.

  • 您链接的[文档](http://msdn.microsoft.com/en-us/library/system.array.aspx)包含此信息,但有点隐藏:_“从.NET Framework 2.0开始,`Array ` 类实现 `System.Collections.Generic.IList&lt;T&gt;`、`System.Collections.Generic.ICollection&lt;T&gt;` 和 `System.Collections.Generic.IEnumerable&lt;T&gt;` 通用接口。提供了实现在运行时转换为数组,因此泛型接口不会出现在 Array 类的声明语法中。"_ (2认同)