zoukankan      html  css  js  c++  java
  • 陌生的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)结束。

  • 相关阅读:
    oracle 数据库服务名怎么查
    vmware vsphere 6.5
    vSphere虚拟化之ESXi的安装及部署
    ArcMap中无法添加ArcGIS Online底图的诊断方法
    ArcGIS中字段计算器(高级计算VBScript、Python)
    Bad habits : Putting NOLOCK everywhere
    Understanding the Impact of NOLOCK and WITH NOLOCK Table Hints in SQL Server
    with(nolock) or (nolock)
    What is “with (nolock)” in SQL Server?
    Changing SQL Server Collation After Installation
  • 原文地址:https://www.cnblogs.com/cgzwwy/p/1656544.html
Copyright © 2011-2022 走看看