yield个人理解及简明示例
1.写法有2种:
yield return <expression>和yield break
yield用于在迭代中返回一个值,并将值带入下一次迭代中。yield break则意味着停止迭代。纯粹的文字描述,一千个人有一千个说法,还是用代码更容易说清楚。
2.官方示例(略带修改):
private void button1_Click(object sender, EventArgs e)
{
string s = string.Empty;
foreach (int i in List.Power(2,8))
{
s += i.ToString() + ",";
}
MessageBox.Show(s);
}
public class List
{
//using System.Collections;
public static IEnumerable Power(int number, int exponent)
{
int counter = 0;
int result = 1; while (counter++ < exponent)
{
result = result * number;
yield return result;
}
}
}
运行示例,发现power方法中的while代码部分,每循环执行一次,即输出一个值,并将这个值带入下一次循环,而power函数并没有每次被调用。
为了验证,我们修改下官方示例代码,来看看我们的判断是否有误:
private void button1_Click(object sender, EventArgs e)
{
string s = string.Empty;
foreach (int i in List.Power())
{
s += i.ToString() + ",";
}
MessageBox.Show(s);
}
public static IEnumerable Power()
{
int counter = 0;
int result = 1;
int number = 2, exponent = 8;
while (counter++ < exponent)
{
result = result * number;
yield return result;
}
}
运行结果与官方示例相同,说明.net framework每次只把yield部分所在的部分代码进行了迭代返回处理。
3.官方的另一个示例为用yield作为属性(输出方式略有修改)。
private void button2_Click(object sender, EventArgs e)
{
var theGalaxies = new Galaxies();
string ps = string.Empty;
foreach (Galaxy theGalaxy in theGalaxies.NextGalaxy)
{
ps += (theGalaxy.Name + " " + theGalaxy.MegaLightYears.ToString() + " >> ");
}
MessageBox.Show(ps);
}
public System.Collections.Generic.IEnumerable<Galaxy> NextGalaxy
{
get
{
yield return new Galaxy { Name = "Tadpole", MegaLightYears = 400 };
yield return new Galaxy { Name = "Pinwheel", MegaLightYears = 25 };
yield return new Galaxy { Name = "Milky Way", MegaLightYears = 0 };
yield return new Galaxy { Name = "Andromeda", MegaLightYears = 3 };
} }
输出结果:

从这个例子可以看出yield其实就是临时中断执行,输出后继续执行而已。
可以修改下这个例子,看效果如何:
public class Galaxies
{
List<Galaxy> ls = new List<Galaxy>();
public System.Collections.Generic.IEnumerable<Galaxy> NextGalaxy
{
get
{
yield return new Galaxy { Name = "Tadpole", MegaLightYears = 400 };
yield return new Galaxy { Name = "Pinwheel", MegaLightYears = 25 };
yield return new Galaxy { Name = "Milky Way", MegaLightYears = 0 };
yield return new Galaxy { Name = "Andromeda", MegaLightYears = 3 };
} }
public System.Collections.Generic.IEnumerable<Galaxy> NextGalaxy1
{ get
{
ls.Add(new Galaxy { Name = "Tadpole", MegaLightYears = 400 });
ls.Add(new Galaxy { Name = "Pinwheel", MegaLightYears = 25 });
ls.Add(new Galaxy { Name = "Milky Way", MegaLightYears = 0 });
ls.Add(new Galaxy { Name = "Andromeda", MegaLightYears = 3 });
int i = -1;
while (i++ < ls.Count - 1)
{
yield return ls[i];
}
}
}
}
调用NextGalaxy1后,结果与官方示例结果相同,还可以进一步修改NextGalaxy1,使其更容易别理解:
public System.Collections.Generic.IEnumerable<Galaxy> NextGalaxy1
{ get
{
ls.Add(new Galaxy { Name = "Tadpole", MegaLightYears = 400 });
ls.Add(new Galaxy { Name = "Pinwheel", MegaLightYears = 25 });
ls.Add(new Galaxy { Name = "Milky Way", MegaLightYears = 0 });
ls.Add(new Galaxy { Name = "Andromeda", MegaLightYears = 3 });
int i = 0;
while (i < ls.Count)
{
yield return ls[i];
i++;
}
}
}
这样看来就很容易理解其含义了,更进一步说就是一边给你输出结果,一边继续给你执行代码,一举两得!
如果想中断执行,则直接用yield break即可。
代码如下:
public System.Collections.Generic.IEnumerable<Galaxy> NextGalaxy1
{ get
{
ls.Add(new Galaxy { Name = "Tadpole", MegaLightYears = 400 });
ls.Add(new Galaxy { Name = "Pinwheel", MegaLightYears = 25 });
ls.Add(new Galaxy { Name = "Milky Way", MegaLightYears = 0 });
ls.Add(new Galaxy { Name = "Andromeda", MegaLightYears = 3 });
int i = -1;
while (i++ < ls.Count - 1)
{
yield return ls[i];
if (ls[i].MegaLightYears == 0)
{
yield break;
} }
}
}
输出结果为:

附官方链接:http://msdn.microsoft.com/zh-cn/library/9k7k7cf0.aspx
yield个人理解及简明示例的更多相关文章
- yield的理解
yield的理解:yield命令是异步两个阶段的分界线需要先对迭代器和生成器进行理解: 迭代器:是一种支持next()操作的对象.它包含一组元素,当执行next()时,返回其中一个元素:当所有元素都被 ...
- [llvm] LLVM 核心类简明示例 : llvm::Value && llvm::Type && llvm::Constant
LLVM 核心类简明示例 : llvm::Value && llvm::Type && llvm::Constant llvm核心类位于 include/llvm/IR ...
- 转载yield关键字理解
实现IEnumerable接口及理解yield关键字 [摘要]本文介绍实现IEnumerable接口及理解yield关键字,并讨论IEnumerable接口如何使得foreach语句可以使用. 本 ...
- C#中yield关键字理解
yield关键字之前用得较少,但是在做项目开发的过程中也遇到了,当时有点迷惑,就顺便研究学习了一下,以下是个人理解,不到之处欢迎拍砖!废话就到这,上代码: class Program { static ...
- 对yield 的理解
最近在学习Python的时候看到yield的相关语法,感觉很独特,相比其他如C/C++的语法比较有意思,于是在看完资料相关章节做一个总结. yield 是一个类似于 return的语法,但是对于ret ...
- 迭代器,生成器,yield,yield from理解
迭代器 说到迭代器就得想说可迭代对象Iterable,实现了__iter__()方法的对象都是可迭代对象,例如很多容器,list ,set, tuples.使用iter方法可以把一个可迭代对象变成迭代 ...
- iOS 浅复制和深复制的深层理解,含示例
转载:https://www.zybuluo.com/MicroCai/note/50592 版权归 @MicroCai 所有 以下是正文: 浅复制就是指针拷贝:深复制就是内容拷贝. 集合的浅复制 ( ...
- Python yield函数理解
Python中的yield函数的作用就相当于一个挂起,是不被写入内存的,相当于一个挂起的状态,用的时候迭代,不用的时候就是一个挂起状态,挂起状态会以生成器的状态表现
- Python中yield深入理解
众所周知,python中的yield有这样的用法: def test(alist): for i in alist: yield i 这样,这个test函数就变成了一个生成器,当每次调用的时候,就会自 ...
随机推荐
- hdu 2093
ps:这题的输入我看到括号以为要用字符串,谁知道看了大神的才知道可以这样"scanf("%d(%d)",&a,&b);" 觉得好神奇.. 然后 ...
- hibernate内部测试题(附赠答案)
一.选择题(共25题,每题2.5分,选择一项或多项,漏选错选不得分) 1.在Hibernate中,以下关于主键生成器说法错误的是( ). A.increment可以用于类型为long.short或by ...
- KVC/KVO原理详解及编程指南
一.简介 1.KVC简介 2.KVO简介 二.KVC相关技术 1.Key和Key Path 2.点语法和KVC 3.一对多关系(To-Many)中的集合访问器方法 4.键值验证(Key-Value V ...
- bigworld源码分析(1)—— 研究bigworld的意义和目标
对于网络游戏服务器开发熟悉的人,基本都知道bigworld引擎,此引擎包括客户端部分和服务器部分,已经有很多知名的网络游戏通过bigworld来构建游戏.我主要关注bigworld的服务器部分,它是一 ...
- 为什么TCP连接不可靠
原文链接:http://watter1985.iteye.com/blog/1924977 原文在此 这篇文章是关于TCP网络编程的一个不起眼的小问题.几乎人人都并不太明白这个问题是怎么回事.曾经我以 ...
- python import eventlet包时提示ImportError: cannot import name eventlet
root@zte-desktop:/home/ubuntu/python-threads# cat eventlet.py #!/usr/bin python import eventlet from ...
- CentOS 6.6 中中文输入法设置
排版比较乱你,参见 https://www.zybuluo.com/Jpz/note/144597 Linux开发环境配置 安装完系统之后,我们需要设置中文输入法,中文输入法是系统自带的,设置步骤如下 ...
- xmimd的第十天笔记
- 使用 CSS 去掉 iPhone 网页上按钮的超大圆角默认样式
使用 iPhone 上的浏览器去浏览网页的时候,按钮总是显示超大圆角的样式,显得超级恶心,但是我们自己定义 border-radius 为 0 也无法去除这个圆角,经过搜索发现这是 webikt 内核 ...
- Quartus 编译错误
1.Error (10028): Can't resolve multiple constant drivers for net ** 这种错误一般是由于定义的reg寄存器在多个always中进行赋值 ...