What is the yield keyword used for in C#?

The yield keyword actually does quite a lot here.

The function returns an object that implements the IEnumerable<object> interface. If a calling function starts foreaching over this object, the function is called again until it "yields". This is syntactic sugar introduced in C# 2.0. In earlier versions you had to create your own IEnumerable and IEnumerator objects to do stuff like this.

The easiest way understand code like this is to type-in an example, set some breakpoints and see what happens. Try stepping through this example:

public void Consumer()
{
foreach(int i in Integers())
{
Console.WriteLine(i.ToString());
}
} public IEnumerable<int> Integers()
{
yield return 1;
yield return 2;
yield return 4;
yield return 8;
yield return 16;
yield return 16777216;
}

When you step through the example, you'll find the first call to Integers() returns 1. The second call returns 2 and the line yield return 1 is not executed again.

Here is a real-life example:

public IEnumerable<T> Read<T>(string sql, Func<IDataReader, T> make, params object[] parms)
{
using (var connection = CreateConnection())
{
using (var command = CreateCommand(CommandType.Text, sql, connection, parms))
{
command.CommandTimeout = dataBaseSettings.ReadCommandTimeout;
using (var reader = command.ExecuteReader())
{
while (reader.Read())
{
yield return make(reader);
}
}
}
}
}
  • In this case that would be easier, i'm just using the integer here to show how yield return works. The nice things about using yield return is that it's a very quick way of implementing the iterator pattern, so things are evaluated lazly. – Mendelt Dec 22 '08 at 8:35
  • Also worth noting you can use yield break; when you don't want to return any more items.

https://stackoverflow.com/a/39507/3782855

Recently Raymond Chen also ran an interesting series of articles on the yield keyword.

While it's nominally used for easily implementing an iterator pattern, but can be generalized into a state machine.

No point in quoting Raymond, the last part also links to other uses (but the example in Entin's blog is esp good, showing how to write async safe code).

What is the yield keyword used for in C#?的更多相关文章

  1. Behind the scenes of the C# yield keyword(转)

    https://startbigthinksmall.wordpress.com/2008/06/09/behind-the-scenes-of-the-c-yield-keyword/ Behind ...

  2. What is the use of c# “Yield” keyword ?

    What is the use of c# “Yield” keyword ? “Yield keyword helps us to do custom stateful iteration over ...

  3. .NET中的yield关键字

    浅谈yield http://www.cnblogs.com/qlb5626267/archive/2009/05/08/1452517.html .NET中yield关键字的用法 http://bl ...

  4. Python关键字yield详解以及Iterable 和Iterator区别

    迭代器(Iterator) 为了理解yield是什么,首先要明白生成器(generator)是什么,在讲生成器之前先说说迭代器(iterator),当创建一个列表(list)时,你可以逐个的读取每一项 ...

  5. [Python学习笔记-005] 理解yield

    网络上介绍yield的文章很多,但大多讲得过于复杂或者追求全面以至于反而不好理解.本文用一个极简的例子给出参考资料[1]中的讲解,因为个人觉得其讲解最为通俗易懂,读者只需要对Python的列表有所了解 ...

  6. Python yield解析

    Pyhton generators and the yield keyword At a glance,the yield statement is used to define generators ...

  7. yield return,yield break

    转自, http://www.cnblogs.com/kingcat/archive/2012/07/11/2585943.html yield return 表示在迭代中下一个迭代时返回的数据,除此 ...

  8. Beginning Scala study note(2) Basics of Scala

    1. Variables (1) Three ways to define variables: 1) val refers to define an immutable variable; scal ...

  9. PHP生成器Generators

    下文的第一个逐行读取文件例子用三种方式实现;普通方法,迭代器和生成器,比较了他们的优缺点,很好,可以引用到自己的代码中 ,支持的php版本(PHP 5 >= 5.5.0) 后面的yield讲解, ...

随机推荐

  1. WebService 规范

    详见:https://blog.csdn.net/u011165335/article/details/51345224 JAVA 中共有三种WebService 规范,分别是JAX-WS(JAX-R ...

  2. 解决mysql登录警告问题

    一.前言 我们在登录mysql的时候经常会看到一句警告: Warning: Using a password on the command line interface can be insecure ...

  3. Ubuntu18.04开机启动sudo命令

    首先接前文:ubuntu18.04 下启动Android Studio报错KVM is required to run this AVD. /dev/kvm device: permission de ...

  4. centos6.x下让redis以服务方式运行

    1.从官网下载redis-2.8.9.tar.gz之后,将redis解压在/usr/local下,目录是redis-2.8.9,然后按照官网给出的办法安装redis即可. 2.安装完在redis-2. ...

  5. Harbor高可用理论及实践(汇聚篇)

    目录 一.理论概述 什么是harbor harbor要解决的问题 有了docker自带的registry为什么还要用harbor harbor的架构组件 Harbor工作原理 二.部署harbor及其 ...

  6. Dism++备份还原系统

    使用dism++备份和还原需要下载该工具,并选择与系统对应的Dism++x64或Dism++x32运行进行操作. Dism++网络下载地址:http://www.chuyu.me/zh-Hans/in ...

  7. java - day016 - IO续(输入输出), 手写双向链表

    课程回顾 对象的创建过程 类加载 加载父类,父类的静态变量分配内存 加载子类,子类的静态变量分配内存 父类静态变量赋值运算, 和静态初始化块 子类静态变量赋值运算, 和子类初始化块 创建对象 创建父类 ...

  8. python实现查找算法

    搜索是在一个项目集合中找到一个特定项目的算法过程.搜索通常的答案是真的或假的,因为该项目是否存在. 搜索的几种常见方法:顺序查找.二分法查找.二叉树查找.哈希查找 线性查找线性查找就是从头找到尾,直到 ...

  9. python pip获取所有已安装的第三包

    pip freeze > requirements.txt # 生成txt 文件 pip install -r requirements.txt # 别人使用时可以直接安装所有的包 [progr ...

  10. svn优点跟缺点?

    优点: 1.svn优点:集中式管理,管理方式在服务端配置好,客户端只需要同步提交即可,使用方便,操作简单,很容易就可以上手 2.在服务端统一控制好访问权限,利用代码的安全管理. 3.所有的代码以服务端 ...