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. spring 容器加载完成后执行某个方法

    理论 刚好再开发过程中遇到了要在项目启动后自动开启某个服务,由于使用了spring,我在使用了spring的listener,它有onApplicationEvent()方法,在Spring容器将所有 ...

  2. Linux 学习之DNS服务器

    概念: DNS:Domain Name System 域名系统 FQDN:Fully Qualified Domain Name 完整主机名 正向解析:由主机名查IP地址 SOA:开始验证(Start ...

  3. Coax Transformers[转载]

    Coax Transformers How to determine the needed Z for a wanted Quarter Wave Lines tranformation ratio ...

  4. Zero

    Zero是我的极品现任BOSS曾用过的QQ昵称.那时候,我正跟京姑娘闹七年之痒,甩她而去赋闲在老家.Zero通过朋友介绍,看了我几篇零散的博客,就给我打电话,让我过来聊聊.本来我跟京姑娘也没有大矛盾, ...

  5. POJ 3416 Crossing --离线+树状数组

    题意: 给一些平面上的点,然后给一些查询(x,y),即以(x,y)为原点建立坐标系,一个人拿走第I,III象限的点,另一个人拿II,IV象限的,点不会在任何一个查询的坐标轴上,问每次两人的点数差为多少 ...

  6. HDU 3667 费用流(拆边)

    题意:有n个城市(1~n),m条有向边:有k件货物要从1运到n,每条边最多能运c件货物,每条边有一个危险系数ai,经过这条路的费用需要ai*x2(x为货物的数量),问所有货物安全到达的费用. 思路:c ...

  7. Socurce Insight 快捷键

    1. 高亮当前选中的的 变量 Shift + F8

  8. UITextView限制字数与行数

    - (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSSt ...

  9. 手机中点击链接或button按钮出现黄色边框的解决办法

    a,input,button{outline: none; -webkit-tap-highlight-color: rgba(255, 255, 255, 0); -webkit-focus-rin ...

  10. 查询各个商品分类中各有多少商品的SQL语句

    SELECT goods_category_id ,count(*) FROM `sw_goods` group by goods_category_id