65.9K
CodeProject 正在变化。 阅读更多。
Home

如何使用 IEnumerable/IEnumerator 接口

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.96/5 (8投票s)

2012年3月28日

CPOL

1分钟阅读

viewsIcon

46368

本文档描述了如何使用 IEnumerable/IEnumerator 接口处理集合类型。

引言

IEnumerable 是 .NET 中 System.Collecetion 类型实现的一个接口,它提供了迭代器模式。根据 MSDN 的定义是

“暴露枚举器,支持对非泛型集合进行简单的迭代。”

这意味着你可以对其进行循环遍历。这可能是一个 ListArray,或者任何支持 foreach 循环的其他类型。IEnumerator 允许你迭代 ListArray 并逐个处理每个元素。

目标

探索在用户自定义类中使用 IEnumerableIEnumerator 的方法。

使用代码

首先展示 IEnumerableIEnumerator 的工作方式:我们定义一个 stringList,并使用迭代器模式遍历每个元素。

// This is a collection that eventually we will use an Enumertor to loop through
// rather than a typical index number if we used a for loop.
string[] Continents = new string[] { "Asia", "Europe", "Africa", "North America", "South America", "Australia", "Antartica" };
 

现在我们已经知道如何使用 foreach 循环遍历每个元素了

// Here is where loop iterate over each item of collection
foreach(string continent in Continents)
{
    Console.WriteLine(continent);
}

同样可以使用 IEnumerator 对象来完成。

// HERE is where the Enumerator is gotten from the List object

IEnumerator enumerator = Continents.GetEnumerator()

while(enumerator.MoveNext())
{
    string continent = Convert.ToString(enumerator.Current);
    Console.WriteLine(continent);
}

关注点

这是第一个优势:如果你的方法接受一个 IEnumerable 而不是一个 ArrayList,它们会变得更强大,因为你可以将不同类型的对象传递给它们。

第二个也是最重要的优势在于,与 ListArray 不同,迭代器块在内存中只保存一个项目,因此如果你正在从大型 SQL 查询中读取结果,你可以将内存使用限制为单个记录。此外,这种评估是延迟的。因此,如果你在读取它时对可枚举对象进行复杂的处理,那么这些处理不会发生,直到被要求时才会执行。

© . All rights reserved.