1. 为什么要使用迭代器,它的由来,请见(1)学习数组,集合,IEnumerable接口,引申学习迭代器

2. 规则
2.1 迭代器是可以返回相同类型的值的有序序列的一段代码.
2.2 迭代器可用作方法,运算符或get访问器的代码体.
2.3 迭代器代码使用yield return语句依次返回每个元素.yield break将终止迭代.
2.4 可以在类中实现多个迭代器.每个迭代器都必须像任何类成员一样有唯一的名称,并且可以在foreach语句中被客户端代码调用,如下所示:foreach(int x in SampleClass.Iterator2){}
2.5 迭代器的返回类型必须为IEnumerable,IEnumerator,IEnumerable<T>或IEnumerator<T>.

3. 下面尽可能多的举使用迭代器的例子,加深理解
例2.1
protected void Page_Load(object sender, EventArgs e)
{
    foreach (int iResult in Power(2, 8))
    {
        lblName.Text += iResult.ToString() + ",";
    }
}

//求幂 iNumber数 iExponent指数
public static IEnumerable Power(int iNumber, int iExponent)
{
    int iCounter = 0;
    int iResult = 1;
    while (iCounter++ < iExponent)
    {
        iResult = iResult * iNumber;
        yield return iResult;
    }
}

相关文章:

  • 2021-08-20
  • 2022-02-10
  • 2021-03-31
  • 2021-06-03
  • 2022-12-23
  • 2021-05-31
  • 2021-05-10
  • 2021-11-07
猜你喜欢
  • 2021-11-13
  • 2021-12-27
  • 2021-12-30
  • 2021-12-14
  • 2022-12-23
  • 2021-07-06
相关资源
相似解决方案