zoukankan      html  css  js  c++  java
  • C#中的yield关键字

    yield  
        关键字yield:在迭代器块中用于向枚举数对象提供值或发出迭代结束信号。迭代器块有两个特殊语句:   
              ●yield return <expression_r_r_r_r>;   
              ●yield break;
      迭代器块  
        迭代器块是有一个或多个yield语句的代码块。下面三种类型的代码块中的任意一种都可以是迭代器块:   
              ■方法主体   
              ■访问器主体   
              ■运算符主体
      yield语句只能出现在迭代器块中,该块可用作方法、运算符或访问器的体。这类方法、运算符或访问器的体受以下约束的控制:  
            ■不允许不安全块。   
            ■方法、运算符或访问器的参数不能是 ref 或 out。   
            ■yield语句不能出现在匿名方法中。   
            ■yield return语句不能出现在catch 块中或含有一个或多个catch子句的try块中。
          yield语句的迭代块可以产生IEnumerator和IEnumerable两种对象:  
    ★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());   
            }   
    ★IEnumerator对象:   
    public IEnumerator<int> GetEnumerator()//注意方法名   
            {   
    yield return 0;   
    yield return 1;   
    yield return 2;   
    yield return 3;   
            }   
        使用示例1:无法直接用于foreach语句,获取迭代器的方法名可任意选择,如MyEnumerator().   
            Integers ints = new Integers();//Integers是GetEnumerator()方法所在的类。   
            IEnumerator<int> enumerator = ints.GetEnumerators();   
    while (enumerator.MoveNext())   
            {   
                Console.WriteLine(enumerator.Current.ToString());   
            }   
        使用示例2:可以作用于foreach语句,但是是方法所在的类用在foreach语句中,并且必须使用GetEnumerator作为获取迭代器的方法名。   
            Integers ints = new Integers();//Integers是GetEnumerator()方法所在的类。   
    foreach (int i in ints)   
            {   
                Console.WriteLine(i.ToString());   
            }

  • 相关阅读:
    常用linux命令
    console页面进去太慢优化
    CentOS7 查看最大线程连接数
    外部ssh连接Ubuntu系统
    Ubantu 防火墙管理
    oracle 闪回
    oracle用户密码过期
    base64编码原理
    Linux 备份数据库mysql
    python静态方法-类方法
  • 原文地址:https://www.cnblogs.com/zhijianliutang/p/2804115.html
Copyright © 2011-2022 走看看