• 陌生的yield关键字



    yield关键字有什么功能,估计大部分人都跟我先前一样一头雾水。我对他产生关注是在做一份面试题之后。

    我查了一下Msdn关于yield 的描述:在迭代器块中用于向枚举数对象提供值或发出迭代结束信号。

    还是一头雾水吧。我来说一下我的理解吧,yield在循环体中出现,在每次循环返回当次运算结果;yield是跟return或者break连用,充当方法输出的标记。

    yield return和return的区别:

    例如:

    int n=1;

    int m=100;

    while(n<100)

    {

        n+=n;

        yield return n;//result 2,4,8,......

    }

    return是整个方法执行终止,并且返回当前结果。

    yield return是当次循环介绍,返回当次结果,并开始下一次循环。

    使用yield关键字的方法的返回值一般为IEnumerable。

    Msdn yield示例代码的的执行过程。

    在下面的示例中,迭代器块(这里是方法 Power(int number, int power))中使用了 yield 语句。当调用 Power 方法时,它返回一个包含数字幂的可枚举对象。注意 Power 方法的返回类型是 IEnumerable(一种迭代器接口类型)。

    using System;
    using System.Collections;
    public class List
    {
        public static IEnumerable Power(int number, int exponent)
        {
            int counter = 0;
            int result = 1;                             //<---------------(2)
            while (counter++ < exponent)      //<---------------(3)
            {
                result = result * number;
                yield return result;
            }
        }

        static void Main()
        {
            // Display powers of 2 up to the exponent 8:
            foreach (int i in Power(2, 8))       //<-----------------(1)
            {
                Console.Write("{0} ", i);        //<-----------------(4)
            }
        }
    }

    返回的结果:2 4 8 16 32 64 128 256。

    首先程序执行到(1),跳到Power方法执行至(2),首次进入(3),返回结果至(4)输出,(1)的下一个循环开始直接从(3)开始,返回结果(4)结束。

  • 相关阅读:
    使群辉支持NTFS(未完善)
    docker 解决 Dockerfile同级文件有其他文件 导致docker build包越来越大
    nginx location配置前后端地址
    前端 Umi框架自带的proxy功能请求后端地址
    linux常用命令
    arthas的使用(正常部署+服务docker部署)
    linux
    oracle行转列,列转行函数的使用(listagg,xmlagg)
    oracle 使用函数 ROW_NUMBER() OVER(PARTITION BY 列 ORDER BY 列 排序 ),自关联日志表,将列数据转换为 行数据
    oracle merge into用法
  • 原文地址:https://www.cnblogs.com/cgzwwy/p/1656544.html
Copyright © 2020-2023  润新知