zoukankan      html  css  js  c++  java
  • yieid 使用笔记

    实例代码:

     1 using System;
     2 using System.Collections;
     3 
     4 public class List
     5 {
     6 
     7     //来源: http://hi.baidu.com/jiang_yy_jiang
     8     public static IEnumerable Power(int number, int exponent)
     9     {
    10         int counter = 0;
    11         int result = 1;
    12         while (counter++ < exponent)
    13         {
    14             result = result * number;
    15             yield return result;
    16         }
    17     }
    18 
    19     static void Main()
    20     {
    22         foreach (int i in Power(2, 8))
    23         {
    24             Console.Write("{0} ", i);
    25         }
    26     }
    27 }

    yield 在迭代器块中用于向枚举数对象提供值或发出迭代结束信息号。

      yield return **; // 返回枚举值,

          yield break; // 发出迭代终止信号

    yield语句只能出现在迭代器块中,该块可用作方法、运算符或访问器的体。这类方法、运算符或访问器的体受以下约束的控制:
            ■不允许不安全块。
            ■方法、运算符或访问器的参数不能是 ref 或 out。
            ■yield语句不能出现在匿名方法中。
            ■yield return语句不能出现在catch 块中或含有一个或多个catch子句的try块中。

    yield语句的迭代块可以产生IEnumerator和IEnumerable两种对象:     

    public IEnumerable<int> GetInts()
    {
         yield return 0;
         yield return 1;
         yield return 2;
         yield return 3;
    }
    
    //可以直接在foreach语句中使用
    
    foreach (int i in GetInts())
    {
         Console.WriteLine(i.ToString());
    }
    
    // 输出结果为0123
    public IEnumerator<int> GetEnumerator()//注意方法名
    {
         yield return 0;
         yield return 1;
         yield break;  
         yield return 3;
    }
    
     //IEnumerator无法直接用于foreach语句,所以可以使用如下语句
    
    
    Integers ints = new Integers();//Integers是GetEnumerator()方法所在的类。
    IEnumerator<int> enumerator = ints.GetEnumerator();
    
    while (enumerator.MoveNext())
    {
         Console.Write("{0} ", enumerator.Current.ToString());
    }
    
    // 输出结果为01

     

     

  • 相关阅读:
    用python爬虫抓站的一些技巧总结
    使用python爬虫抓站的一些技巧总结:进阶篇
    Python模块学习:threading 多线程控制和处理
    Redis操作命令总结
    Redis介绍
    linux内核设计与实现笔记 进程调度
    Python常见数据结构整理
    Linux进程调度原理
    Python yield
    Qt之布局管理器
  • 原文地址:https://www.cnblogs.com/sunleinote/p/3049355.html
Copyright © 2011-2022 走看看