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 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.
- 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讲解, ...
随机推荐
- Jerry Wang从2017年到2019年的自由泳学习笔记
打腿 把注意力调整到脚部,尽量不要让他打出水面,因为在空气中大腿完全是无用功,但是如果只是脚跟出水一点,倒也没什么关心,但是主观上,要控制一下,如果你听到你的打腿是"咚咚咚咚"这样 ...
- c# 类嵌套
- 【OF框架】在Visual Studio中发布Docker镜像,推送镜像到Azure容器注册表
准备 拥有Azure账号,已经创建 Azure容器注册表,获得注册表地址.账号.密码 本地已经在Visual Studio登录Azure账号. 本地已经拥有Docker环境 注意:首次发布Docker ...
- 每日一题-——LeetCode(78)子集
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集).输入: nums = [1,2,3]输出:[ [3], [1], [2], [1,2,3], [1,3], [2, ...
- Ansible批量自动化管理工具
一,工具与环境介绍 1.1 ansible简介 批量管理服务器的工具 无需部署agent,通过ssh进行管理 流行的自动化运维工具:https://github.com/ansible/ansible ...
- osi七层网络模型(一)
在网络中OSI分为七层网络模型,怎么理解七层模型呢?简单理解我们的手机都有手机壳.屏幕.摄像头.电池.芯片等很多原件,每个原件都是由不同的 厂家生产,最终组装成了一部功能完整的手机,同样,在网络中,也 ...
- 解决Hibernate validator抛出Ljavax/validation/ParameterNameProvider异常方法
最近升级CAS Client4.0客户端Spring版本至Spring4.*以上,升级整合hibernate框架时,Hibernate validator 4.3.0.Final使用版本(从Hiber ...
- 2019-ACM-ICPC-徐州站网络赛- I. query-二维偏序+树状数组
2019-ACM-ICPC-徐州站网络赛- I. query-二维偏序+树状数组 [Problem Description] 给你一个\([1,n]\)的排列,查询\([l,r]\)区间内有多少对 ...
- 0022SpringMVC解决post请求中文乱码的问题
我们在页面难免提交一些中文数据给后台处理,但是发现后台拿到的数据乱码,可以在每一个controller中都设置编码,但是太过于麻烦, 正确的解决办法应该是在web.xml中配置解决中文乱码的过滤器: ...
- python_面向对象——多态
1.同一接口,多种形态 class Document: def __init__(self,name): self.name = name def show(self): # 异常处理:提示子类必须把 ...