.Net 2.0里有一个有用的新功能:迭代器

下面内容节选至MSDN2005。

迭代器(C# 编程指南) 

迭代器是 C# 2.0 中的新功能。迭代器是方法、get 访问器或运算符,它使您能够在结构中支持 foreach 迭代,而不必实现整个 IEnumerable 接口。您只需提供一个迭代器,即可遍历类中的数据结构。当编译器检测到迭代器时,它将自动生成 IEnumerableIEnumerable 接口的 CurrentMoveNextDispose 方法。

迭代器概述

  • 迭代器是可以返回相同类型的值的有序序列的一段代码。

  • 迭代器可用作方法、运算符或 get 访问器的代码体。

  • 迭代器代码使用 yield return 语句依次返回每个元素。yield break 将终止迭代。有关更多信息,请参见 yield

  • 可以在类中实现多个迭代器。每个迭代器都必须像任何类成员一样有唯一的名称,并且可以在 foreach 语句中被客户端代码调用,如下所示:foreach(int x in SampleClass.Iterator2){}

  • 迭代器的返回类型必须为 IEnumerableIEnumeratorIEnumerableIEnumerator

yield 关键字用于指定返回的值。到达 yield return 语句时,会保存当前位置。下次调用迭代器时将从此位置重新开始执行。

迭代器对集合类特别有用,它提供一种简单的方法来迭代不常用的数据结构(如二进制树)。

备注备注

yield 语句只能出现在 iterator 块中,该块可用作方法、运算符或访问器的体。这类方法、运算符或访问器的体受以下约束的控制:

  • 不允许不安全块。

  • 方法、运算符或访问器的参数不能是 refout

yield 语句不能出现在匿名方法中。有关更多信息,请参见匿名方法(C# 编程指南)

当和 expression 一起使用时,yield return 语句不能出现在 catch 块中或含有一个或多个 catch 子句的 try 块中。

示例

说明

在本示例中,DaysOfTheWeek 类是将一周中的各天作为字符串进行存储的简单集合类。foreach 循环每迭代一次,都返回集合中的下一个字符串。


C#

public class DaysOfTheWeek : System.Collections.IEnumerable
{
    
string[] m_Days = { "Sun""Mon""Tue""Wed""Thr""Fri""Sat" };

    
public System.Collections.IEnumerator GetEnumerator()
    {
        
for (int i = 0; i < m_Days.Length; i++)
        {
            yield 
return m_Days[i];
        }
    }
}

class TestDaysOfTheWeek
{
    
static void Main()
    {
        
// Create an instance of the collection class
        DaysOfTheWeek week = new DaysOfTheWeek();

        
// Iterate with foreach
        foreach (string day in week)
        {
            System.Console.Write(day 
+ " ");
        }
    }
}

输出:
Sun Mon Tue Wed Thr Fri Sat

在下面的示例中,迭代器块(这里是方法 Power(int number, int power))中使用了 yield 语句。当调用 Power 方法时,它返回一个包含数字幂的可枚举对象。注意 Power 方法的返回类型是 IEnumerable(一种迭代器接口类型)。
// yield-example.cs
using System;
using System.Collections;
public class List
{
    
public static IEnumerable Power(int number, int exponent)
    {
        
int counter = 0;
        
int result = 1;
        
while (counter++ < exponent)
        {
            result 
= result * number;
            yield 
return result;
        }
    }

    
static void Main()
    {
        
// Display powers of 2 up to the exponent 8:
        foreach (int i in Power(28))
        {
            Console.Write(
"{0} ", i);
        }
    }
}
输出:
2 4 8 16 32 64 128 256 

原文地址:https://www.cnblogs.com/Sandheart/p/559063.html