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. iOS NSNotificationCenter 使用姿势详解

    最近在做平板的过程中,发现了一些很不规范的代码.偶然修复支付bug的时候,看到其他项目代码,使用通知的地方没有移除,我以为我这个模块的支付闪退是因为他通知没有移除的缘故.而在debug和看了具体的代码 ...

  2. selenium模拟H5触摸滑动之-TouchAction

    最近做移动端H5页面的自动化测试时候,需要模拟一些上拉,下滑的操作,最初考虑使用使用selenium ActionChains来模拟操作,但是ActionChains 只是针对PC端程序鼠标模拟的一系 ...

  3. TestNG并发执行用例详解和范例

    前言 TestNG有多种并发方式支持,方法的并发,class级的并发,test级的并发等:根据实际应用可以灵活的配置和使用,下面分别对几种并发方法进行说明: 一.方法级并发 方法级并发即method级 ...

  4. TLS1.3 认证和秘钥建立握手环节的分析

    1.ClientHello 中的参数 ClientHello---{   Random_C .extension }   在 extension中的扩展中包含 ( supported_version ...

  5. [networking][sdn] BGP/EGP/IGP是什么

    引子 这是一个惊悚的故事,胆小的人不要点开.整个故事,是从这张图开始的. 整个图,分左中右三块.左边是tom和他所在的网络.右边是jerry和他所在的网络.这两个网络可以在世界上的任何一个角落.彼此有 ...

  6. Windows 网络凭证

    前言 单位内部,员工之间电脑免不了要相互访问(eg:访问共享文件夹).这就引出网络凭证的概念,即你用什么身份访问对端计算机. 实验环境 创建共享文件夹 WinSrv 2008上新建的文件夹shared ...

  7. Redis数据缓存淘汰策略【FIFO 、LRU、LFU】

    FIFO.LFU.LRU FIFO:先进先出算法 FIFO(First in First out),先进先出.在FIFO Cache设计中,核心原则就是:如果一个数据最先进入缓存中,则应该最早淘汰掉. ...

  8. mysql官方下载安装教程(centos)

    Linux下Mysql 5.6.30 tar包安装 (2016-04-27 22:45:39) 转载▼ 环境:centos 6.4 x64 先下载mysql安装包 打开 http://dev.mysq ...

  9. 通过自定义属性获取指定checkbox是否选中

    $("input[conferid='"+conferid+"']").is(':checked'); $("input[conferid='1234 ...

  10. P1899 魔法物品

    题目描述 //又是一个好(nan)题好(nan)题 //首先,普通物品一开始就卖掉就可以,因为它不会增值 //至于魔法物品 //如果一个魔法物品使用了卷轴后的价值减去买卷轴的钱还不如鉴定前的价值高,那 ...