c# - 理解 C# 中的 IEnumerable<T>

标签 c# .net collections ienumerable

我正在尝试理解 IEnumerable C#中的接口(interface)。正如 MSDN 中所述
IEnumerable公开一个枚举器,它支持对非泛型集合的简单迭代。这很简单。当我们有一个实现这个接口(interface)的集合时,我们得到一个枚举器,它实现了 IEnumerator。接口(interface) ( http://msdn.microsoft.com/en-us/library/system.collections.ienumerable.getenumerator(v=vs.110).aspx ),并使用此枚举器,我们可以通过如下方式遍历集合的所有元素:

foreach(var item in items)
{
    // code goes here
}

在上面的代码片段中,items是一个实现 IEnumerable 的集合界面。这是可能的,因为枚举器有一个名为 Current 的属性。 ,它有集合的当前元素和一个方法 MoveNext ,由枚举器使用,移动到下一个元素。最后但同样重要的是,它有一个名为 Reset 的方法。 ,它将枚举器设置为其初始位置,即集合中第一个元素之前的位置,如 MSDN 中所述。

让我们有以下代码片段:

int[] array = new int[10] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
IEnumerable<int> numbers = array;
foreach (var number in numbers)
{
    Console.WriteLine(number);
}

在上面的代码片段中,我们初始化了一个整数数组,然后我们定义了一个 IEnumerable 类型。指向数组。自 numbers实现 IEnumerable ,我们可以使用上面的 foreach 遍历它的元素.

我认为当我们定义 numbers 时,幕后的编译器会发出一些代码。然后尝试遍历它的元素。其实我发现Array工具 IEnumerable<T> .

我的问题是每次我们定义一个数组时,因为数组是一个实现了 IEnumerable 的对象。和 IEnumerator ,相应的方法是由编译器实现的?

在此先感谢您的帮助!

最佳答案

你的问题,

My question is every time we define an array, since an array is an object that implements IEnumerable and IEnumerator, the corresponding methods are implemented by the compiler?

根据 MSDN documentation Remarks 部分明确提到,

Starting with the .NET Framework 2.0, the Array class implements the System.Collections.Generic.IList<T>, System.Collections.Generic.ICollection<T>, and System.Collections.Generic.IEnumerable<T> generic interfaces. The implementations are provided to arrays at run time, and therefore are not visible to the documentation build tools. As a result, the generic interfaces do not appear in the declaration syntax for the Array class, and there are no reference topics for interface members that are accessible only by casting an array to the generic interface type (explicit interface implementations). The key thing to be aware of when you cast an array to one of these interfaces is that members which add, insert, or remove elements throw NotSupportedException.

是的,编译器在运行时将实现提供给数组。

编辑您在评论中的问题

That happens with all the non-generic collections?

阅读帖子后,

在查看所有 Collections 之后,我发现 ArrayList , BitArray等都是集合,但不实现任何通用接口(interface)。

如果我错了请纠正我 我不认为所有 Collection 的实现都是如此将在运行时提供。

关于c# - 理解 C# 中的 IEnumerable<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20543151/

相关文章:

C# 字符串到带时区的 DateTime

c# - WPF Datagrid 不显示文本

c# - ASP.NET Core 托管和服务器端 Blazor 之间到底有什么区别?

c# - 在 WebBrowser 文档中获取鼠标点击坐标

.net - 使用 linq 将 list<t> 分解成许多长度为 n 的 list<t>?

c# - Windows 窗体中列表框内的复选框

c# - 无法加载文件或程序集“Microsoft.IdentityModel.Protocols.WsFederation,

java - 如何使用 JPA/Hibernate 持久保存声明具有几个整数的固定大小数组的字段的实体

java - Hibernate 中 CustomCollectionType 与 UserCollectionType 的预期用例是什么?

c# - 根据2个条件选择使用linq