惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
博客园_首页
雷峰网
雷峰网
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
WordPress大学
WordPress大学
腾讯CDC
T
Tailwind CSS Blog
A
About on SuperTechFans
H
Hackread – Cybersecurity News, Data Breaches, AI and More
The GitHub Blog
The GitHub Blog
T
The Blog of Author Tim Ferriss
G
Google Developers Blog
The Cloudflare Blog
D
DataBreaches.Net
Recent Announcements
Recent Announcements
Engineering at Meta
Engineering at Meta
B
Blog
博客园 - 聂微东
阮一峰的网络日志
阮一峰的网络日志
月光博客
月光博客
博客园 - 司徒正美
MongoDB | Blog
MongoDB | Blog
Google DeepMind News
Google DeepMind News
Apple Machine Learning Research
Apple Machine Learning Research

博客园 - 王伟晔

docker 主从mysql配置 利用asp.net Core开发webapi对接云之家智能审批数据互联控件 Windows 2012安装odoo12 Windows有点腻了?不如试试Ubuntu. 处理范例代码Webapi中的Mongodb的Bson中ObjectId反序列化异常 用app.net Core搞掂多国语言网站 重建程序员能力(3)-asp.net MVC框架增加Controller 重建程序员能力(2)-如何使asp.net mvc应用增加js和其他功能 重建程序员能力(1) asp.net mvc 5发布部署遇到403.14 我需要在Web上完成一个图片上传的功能(+2) 我需要在Web上完成一个图片上传的功能后续(+1) 我需要在Web上完成一个图片上传的功能 android-studio-bundle-141.1980579-windows download Site Razor提高WebPage代码的易读性 C# Hello World - 王伟晔 用params关键字增强代码的可读性 发现Visual Studio隐含的大礼包--漂亮的Visual Studio图像库 职业程序员必须要有的工作态度(之一)
陌生的yield关键字
王伟晔 · 2010-01-26 · via 博客园 - 王伟晔


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)结束。