C#中的yield return

C#语法中有个特别的关键字yield, 它是干什么用的呢?

来看看专业的解释:

yield 是在迭代器块中用于向枚举数对象提供值或发出迭代结束信号。它的形式为下列之一:
yield return <expression>;
yield break

看如下例子:

       public class CustomCollection :IEnumerable {

           public static void Main (string[] args)
{
CustomCollection cc = new CustomCollection (); foreach (String word in cc) {
Console.WriteLine ("word:" +word);
}
} public IEnumerator GetEnumerator(){ yield return "Hello";
yield return "Boys";
yield return "And";
yield return "Girls";
//return new HelloBoyGirls(); }
} // public class HelloBoyGirls: IEnumerator {
// private int cusor = -1;
// private String[] words = {"Hello", "Boys", "And", "Girls"};
//
// public bool MoveNext ()
// {
// cusor++;
// return cusor < words.Length;
// }
//
// public void Reset ()
// {
// cusor = 0;
// }
//
// public object Current {
// get {
// return words [cusor];
// }
// }
// }

上面的例子是实现了一个自定义的迭代器;实现可迭代(可以用foreach)的数据集合,必须实现GetEmumerator()方法,返回实现了IEmumerator的对象实例。

完成这个, 有两种方法,一种是用上面注释掉的代码,一种是用yield return. yield return 需要配合IEmumerator进行使用, 在外部foreach循环中,它会执行GetEmumerator()方法,遇到yield return, 做了如下两件事情:

1.记录下当前执行到的代码位置

2. 将代码控制权返回到外部, yield return 后面的值, 作为迭代的当前值。

当执行下一个循环, 从刚才记录的代码位置后面, 开始继续执行代码。

简单地说, yield return 就是实现IEmumerator的超级简化版, 是不是很简单?

那么问题又来了, yield return 是如何决定循环该结束,yield return 之后的代码, 什么时候执行呢?

把上面的例子改造一下, 不要用方便的foreach了, 用while 循环自己控制:

     public class CustomCollection :IEnumerable {

         public static void Main (string[] args)
{
CustomCollection cc = new CustomCollection (); IEnumerator enumerator = cc.GetEnumerator ();
while (true) {
bool canMoveNext = enumerator.MoveNext ();
Console.WriteLine ("canMoveNext:" +canMoveNext);
if (!canMoveNext)
break;
Object obj = enumerator.Current;
Console.WriteLine ("current obj:" +obj);
}
// foreach (String word in cc) {
// Console.WriteLine ("word:" +word);
// }
Console.WriteLine ("Main End."); } public IEnumerator GetEnumerator(){ yield return "Hello";
yield return "Boys";
yield return "And";
yield return "Girls"; Console.WriteLine ("After all yield returns.");
//return new HelloBoyGirls(); }
}

运行代码, 结果是:

canMoveNext:True
current obj:Hello
canMoveNext:True
current obj:Boys
canMoveNext:True
current obj:And
canMoveNext:True
current obj:Girls
After all yield returns.
canMoveNext:False
Main End.

说明, 在GetEmumerator()中, 只有yield return 语句, 外部调用MoveNext()都为true, current就是yield return后面的对象

除了yield return, 还有yield break; yield break 的作用是, 停止循环, MoveNext()为false, yield break 之后的语句, 不会被执行!

有兴趣的童鞋, 可以自己写个例子试试。

C#中的yield return与Unity中的Coroutine(协程)(上)的更多相关文章

  1. C#中的yield return与Unity中的Coroutine(协程)(下)

    Unity中的Coroutine(协程) 估计熟悉Unity的人看过或者用过StartCoroutine() 假设我们在场景中有一个UGUI组件, Image: 将以下代码绑定到Image using ...

  2. 可惜Java中没有yield return

    项目中一个消息推送需求,推送的用户数几百万,用户清单很简单就是一个txt文件,是由hadoop计算出来的.格式大概如下: uid caller 123456 12345678901 789101 12 ...

  3. C#中的yield return用法演示源码

    下边代码段是关于C#中的yield return用法演示的代码. using System;using System.Collections;using System.Collections.Gene ...

  4. Unity之"诡异"的协程

    为什么说是诡异的协程呢?首先从一个案例说起吧,示例如下: 游戏目标:让小车进入到对应颜色屋子里,即可获得一分.(转弯的道路可控)   为了让小车能够平滑转弯,小车的前进方向需要和车子的位置与圆心组成的 ...

  5. C#中的yield return

    4.1 迭代器块 一个迭代器块(iterator block)是一个能够产生有序的值序列的块.迭代器块和普通语句块的区别就是其中出现的一个或多个yield语句. yield return语句产生迭代的 ...

  6. Android中的Coroutine协程原理详解

    前言 协程是一个并发方案.也是一种思想. 传统意义上的协程是单线程的,面对io密集型任务他的内存消耗更少,进而效率高.但是面对计算密集型的任务不如多线程并行运算效率高. 不同的语言对于协程都有不同的实 ...

  7. Unity脚本编程之——协程(Coroutine)

    本文翻译自Unity官方文档:https://docs.unity3d.com/Manual/Coroutines.html 专有名词: Coroutine 协程 Alpha 不透明度 当你调用一个函 ...

  8. 【Unity笔记】使用协程(Coroutine)异步加载场景

    using UnityEngine; using System.Collections; using UnityEngine.SceneManagement; using System; public ...

  9. Unity带参数的协程

    两种方法都可以传递参数,代码如下: using UnityEngine; using System.Collections; public class Test : MonoBehaviour { v ...

随机推荐

  1. diff, cmp, patch

    diff 以行为单位比较两个文件之间的差异,经常用来查看同一个文件的新旧版本的差异,通常用在文本文件的比较,可以使用重定向'>'制作补丁文档,通常以.patch结尾 \(diff [-bBi] ...

  2. iOS -数据库网络之xml解析之远程解析XML

    1.IOS中XML文件获取    //设置远程访问地址     NSURL *url=[NSURL URLWithString:@""];       //创建动态URL请求,并初 ...

  3. nyoj 115 城市平乱 dijkstra最短路

    题目链接: http://acm.nyist.net/JudgeOnline/problem.php?pid=115 dijkstra算法. #include "stdio.h" ...

  4. 自动化测试selenium+java 第一章

    selenium元素的定位以及操作 1. 元素的定位 Selenium 自动化,我们需要做的最基本的事情就是在页面找到元素并通过脚本程 序去操作这个元素,实现模拟人工操作.我们有多种定位元素的方式可以 ...

  5. runv containerd 流程分析

    当runv需要启动一个容器的时候,首先需要启动containrd,作为该容器的daemon.因此,启动containerd的相关代码也是从runv/start.go开始.最终,启动containerd ...

  6. 如何实现ZBrush中的Alt和Shift键的快速运用

    ZBrush是一个数字雕刻和绘画软件,它以强大的功能和直观的工作流程彻底改变了整个三维雕刻行业.在一个简洁的界面中,ZBrush®为当代数字艺术家提供了世界上最先进的工具.利用快捷键能使操作更快捷高效 ...

  7. 边工作边刷题:70天一遍leetcode: day 71-2

    One Edit Distance 要点:有两种解法要考虑:已知长度和未知长度(比如只给个iterator) 已知长度:最好不要用if/else在最外面分情况,而是loop在外,用err记录misma ...

  8. UVALive 5966 Blade and Sword -- 搜索(中等题)

    题意:给一幅地图,P为起点,D为终点,'*'为传送阵,到达传送阵可以传到任意一个其他的传送阵,传到以后可以正常走或者再传回来,问P->D最短步数. 分析:这题一定要细心,分析要到位才能搞定,错一 ...

  9. WWW压缩解压缩

    unity的WWW参考文档:http://game.ceeger.com/Script/WWW/WWW.html 在unity中把资源打包成Assetbundle其实把资源通过 LZMA 压缩成二进制 ...

  10. java 14 -1 正则表达式

    正则表达式:符合一定规则的字符串. 1.判断QQ号码是否正确的案例: public class RegexDemo2 { public static void main(String[] args) ...