What is the yield keyword used for in C#?
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 foreach
ing 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.
- The implementation of iterators in C# and its consequences (part 1)
- The implementation of iterators in C# and its consequences (part 2)
- The implementation of iterators in C# and its consequences (part 3)
- The implementation of iterators in C# and its consequences (part 4)
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#?的更多相关文章
- Behind the scenes of the C# yield keyword(转)
https://startbigthinksmall.wordpress.com/2008/06/09/behind-the-scenes-of-the-c-yield-keyword/ Behind ...
- 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 ...
- .NET中的yield关键字
浅谈yield http://www.cnblogs.com/qlb5626267/archive/2009/05/08/1452517.html .NET中yield关键字的用法 http://bl ...
- Python关键字yield详解以及Iterable 和Iterator区别
迭代器(Iterator) 为了理解yield是什么,首先要明白生成器(generator)是什么,在讲生成器之前先说说迭代器(iterator),当创建一个列表(list)时,你可以逐个的读取每一项 ...
- [Python学习笔记-005] 理解yield
网络上介绍yield的文章很多,但大多讲得过于复杂或者追求全面以至于反而不好理解.本文用一个极简的例子给出参考资料[1]中的讲解,因为个人觉得其讲解最为通俗易懂,读者只需要对Python的列表有所了解 ...
- Python yield解析
Pyhton generators and the yield keyword At a glance,the yield statement is used to define generators ...
- yield return,yield break
转自, http://www.cnblogs.com/kingcat/archive/2012/07/11/2585943.html yield return 表示在迭代中下一个迭代时返回的数据,除此 ...
- 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 ...
- PHP生成器Generators
下文的第一个逐行读取文件例子用三种方式实现;普通方法,迭代器和生成器,比较了他们的优缺点,很好,可以引用到自己的代码中 ,支持的php版本(PHP 5 >= 5.5.0) 后面的yield讲解, ...
随机推荐
- stm32和sd卡
SD卡从容量上讲分两种:标准容量和大容量,最小的是标准容量,小于等于2G 其中的访问关系如下: SD卡分为两种模式:认证模式和传输模式,每一个模式包含着不同的状态,如下 以下主要讲其初始化过程: SD ...
- SQLSEVER 同台服务器下不同表 触发器实现数据实时同步
触发器的使用: 1.首先建立两个相同结构的表,两个表明的列的名称不同. student_01 字段 name ; 字段 age ; 字段 class ; student_02 字段 ...
- SQL SERVER-邮件配置
存储发邮件 USE msdb GO EXEC sp_send_dbmail @profile_name = 'mail_pro', @recipients='Jinwei.chang@quantacn ...
- 网络编程socketserver
一.网络编程回顾 tcp是流式传输,字节流,数据与数据之间没有边界 优点:不限定长度,可靠传输 缺点:慢,和一端的通信连接conn会一直占用通信资源 udp协议式面向数据包的传输 优点:快,由于不需要 ...
- 为LPC1549 LPCXpresso评估板开发基于mbed的项目
本文将主要介绍如何使用Visual Studio和VisualGDB为LPC1549 LPCXpresso开发板创建一个使用mbed框架的基础项目. LPC1549 LPCXpresso开发板载一个L ...
- Codeforces #366 (Div. 2) D. Ant Man (贪心)
https://blog.csdn.net/liangzhaoyang1/article/details/52215276 原博客 原来好像是个dp题,不过我看了别人的博客使用贪心做的 复杂度(n^ ...
- vue-cli3项目搭建配置以及性能优化
项目初始化 注意:安装前请确保有安装node.js,并且node>=8.9 全局安装vue npm install -g @vue/cli 如果之前安装了vue旧版本,查看vue --versi ...
- 我花了2个月时间,整理了100篇Linux技术精华,技术人必看
一个以技术为立身根基的教育机构做出来的微信号,干货程度会有多高? 马哥Linux运维公众号运营五年,从一开始的定位就是给技术人分享加薪干货的地方.这五年里,公众号运营最重的任务就是做内容.内容并不好做 ...
- Robot Framework--标签Tag
Robot Framework的标签是一个简单而又强大的分类机制,功能如下: 标签在reports,logs以及测试数据中展示,显示关于测试用例的元数据信息 用例的执行统计(total,passed, ...
- 网络编程 --- subprocess模块,struct模块,粘包,UDP协议,socket_server模块
目录 subprocess模块 struct模块 粘包 UDP协议 socket_server模块 subprocess模块 作用: 1.可以帮你通过代码执行操作系统的终端命令 2.并返回终端执行命令 ...