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. Session机制详解及分布式中Session共享解决方案

    一.为什么要产生Session http协议本身是无状态的,客户端只需要向服务器请求下载内容,客户端和服务器都不记录彼此的历史信息,每一次请求都是独立的. 为什么是无状态的呢?因为浏览器与服务器是使用 ...

  2. Lumen5.6使用JWT【最新教程】,亲身失败百次的总结

    一.前言 如果需要使用 Passport,可以参考在下之前的教程: 'Lumen5.4配置OAuth2.0[强迫症,就是要用最新版本的Lumen]' . 由于原作者文档的简洁性,同时 Lumen 下的 ...

  3. Vue路由嵌套和命名视图

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  4. C#-调试记Log文件

    using System.IO; //捕获异常写入Log catch (Exception ex) { string msg = ex.Message + ex.StackTrace; string ...

  5. C++中priority_queue的用法

    本来想自己写一写的,但看到这个随笔,感觉要写的东西跟这个差不多,就直接附上链接. 需要注意事项: rand()函数需要引入头文件#include<cstdlib>. 自定义类型,重载ope ...

  6. python函数式编程-偏向函数

    Python的functools模块提供了很多有用的功能,其中一个就是偏函数(Partial function).要注意,这里的偏函数和数学意义上的偏函数不一样. 在介绍函数参数的时候,我们讲到,通过 ...

  7. SHELL编程基础01

    首先shell是在linux下运行的一种环境,它是以shell脚本来运行的,学会了它基本可以解决任何问题,也可以用shell脚本开发. 和java,python的相比,其弱类型的语言没有那么复杂的结构 ...

  8. 实验十一 团队作业7:团队项目设计完善&编码1

    博文简要信息表: 项目 内容 软件工程 https://www.cnblogs.com/nwnu-daizh/ 本次实验链接地址 https://www.cnblogs.com/nwnu-daizh/ ...

  9. 多任务案例--文件夹copy.py

    import os import multiprocessing def copy_file(q,file_name,new_folder_name,old_folder_name): with op ...

  10. JS闭包是什么?

    闭包是js开发惯用的技巧,什么是闭包? 闭包指的是:能够访问另一个函数作用域的变量的函数. 清晰的讲:闭包就是一个函数,这个函数能够访问其他函数的作用域中的变量. function outer(){ ...