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)
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
)
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)
归档时间: |
|
查看次数: |
25336 次 |
最近记录: |