C# 中的"yield"使用

yield是C#为了简化遍历操作实现的语法糖,我们知道如果要要某个类型支持遍历就必须要实现系统接口IEnumerable,这个接口后续实现比较繁琐要写一大堆代码才能支持真正的遍历功能。举例说明


using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Text; namespace
{
    class Program
    {
        static void Main(string[] args)
        {
            HelloCollection helloCollection = new HelloCollection();
            foreach (string s in helloCollection)
            {
                Console.WriteLine(s);
            }             Console.ReadKey();
        }
    }     //public class HelloCollection : IEnumerable
    //{
    //    public IEnumerator GetEnumerator()
    //    {
    //        yield return "Hello";
    //        yield return "World";
    //    }
    //}     public class HelloCollection : IEnumerable
    {
        public IEnumerator GetEnumerator()
        {
            Enumerator enumerator = new Enumerator(0);
            return enumerator;
        }         public class Enumerator : IEnumerator, IDisposable
        {
            private int state;
            private object current;             public Enumerator(int state)
            {
                this.state = state;
            }             public bool MoveNext()
            {
                switch (state)
                {
                    case 0:
                        current = "Hello";
                        state = 1;
                        return true;
                    case 1:
                        current = "World";
                        state = 2;
                        return true;
                    case 2:
                        break;
                }
                return false;
            }             public void Reset()
            {
                throw new NotSupportedException();
            }             public object Current
            {
                get { return current; }
            }             public void Dispose()
            {
            }
        }
    }
}

上面注释的部分引用了"yield return”,其功能相当于下面所有代码!可以看到如果不适用yield需要些很多代码来支持遍历操作。

yield return 表示在迭代中下一个迭代时返回的数据,除此之外还有yield break, 其表示跳出迭代,为了理解二者的区别我们看下面的例子


class A : IEnumerable
{
    private int[] array = new int[10];     public IEnumerator GetEnumerator()
    {
        for (int i = 0; i < 10; i++)
        {
            yield return array[i];
        }
    }
}

如果你只想让用户访问ARRAY的前8个数据,则可做如下修改.这时将会用到yield break,修改函数如下


public IEnumerator GetEnumerator()
{
    for (int i = 0; i < 10; i++)
    {
        if (i < 8)
        {
            yield return array[i];
        }
        else
        {
            yield break;
        }
    }
}

这样,则只会返回前8个数据.

【转】C# 中的"yield"使用的更多相关文章

  1. 可惜Java中没有yield return

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

  2. 初次使用C#中的yield

    这几天在Python程序员的微信订阅号中总是见到yield的关键字,才想起来在C#中也是有yield,但是只是知道有,从来没有了解过他的用法,今天有时间就来看看是怎么使用的.刚开始肯定就是搜索一下用法 ...

  3. C#中的yield return与Unity中的Coroutine(协程)(上)

    C#中的yield return C#语法中有个特别的关键字yield, 它是干什么用的呢? 来看看专业的解释: yield 是在迭代器块中用于向枚举数对象提供值或发出迭代结束信号.它的形式为下列之一 ...

  4. 关于Python中的yield

    关于Python中的yield   在介绍yield前有必要先说明下Python中的迭代器(iterator)和生成器(constructor). 一.迭代器(iterator) 在Python中,f ...

  5. 关于Python中的yield(转载)

    您可能听说过,带有 yield 的函数在 Python 中被称之为 generator(生成器),何谓 generator ? 我们先抛开 generator,以一个常见的编程题目来展示 yield ...

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

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

  7. python 中的 yield 究竟为何物?生成器和迭代器的区别?

    当你突然看到别人的代码中出现了一个好像见过但又没用过的关键词 比如 yield ,你是否会觉得这段代码真是高大上呢? 或许只有我这种小白才会这样子觉得,就在刚刚,我就看见了别人的代码中的yield,觉 ...

  8. Python中的yield生成器的简单介绍

    Python yield 使用浅析(整理自:廖 雪峰, 软件工程师, HP 2012 年 11 月 22 日 ) 初学 Python 的开发者经常会发现很多 Python 函数中用到了 yield 关 ...

  9. 在 PHP 中使用 `yield` 来做内存优化

    你有没有想过 "在 PHP 中使用 yield 会有什么益处",我将为你节省一些谷歌搜索的时间: 我列出了一些要向你介绍的要点来全面认知 yield: 什么是 yield. yie ...

  10. 深入理解Python中的yield和send

    send方法和next方法唯一的区别是在执行send方法会首先把上一次挂起的yield语句的返回值通过参数设定,从而实现与生成器方法的交互. 但是需要注意,在一个生成器对象没有执行next方法之前,由 ...

随机推荐

  1. python之删除指定目录指定日期下的日志文件

    #=======================================================================================20190521以下脚本 ...

  2. python 之format字符串格式化

    print函数之format字符串格式化方法的使用与学习笔记. 一.映射关系 (1)“映射”示例,以下通过位置举例说明: [+]Example_1: >>> print(" ...

  3. [VC]关于ocx打包为cab的使用

    把打包的工具makecert.exe等放在c:/windows/system32/里才能在dos下面使用 注:如果本机使用可以codebase="http://localhost/testa ...

  4. Expires和Cache-Control

    本文原链接:https://blog.csdn.net/zhouziyu2011/article/details/71312452 浅谈前端性能优化(一)——Expires和Cache-Control ...

  5. 批量格式化json

    单个文件格式化工具: vscode和sublime都有格式化json的插件. 但是笔者遇到的情况是有几百个文件需要格式化,不可能每个文件都打开,进行分别格式化. 于是写了一个python脚本,非常强大 ...

  6. selenium--iframe

    前戏 很多人在用selenium定位页面元素的时候会遇到定位不到的问题,明明元素就在那儿,用firebug也可以看到,就是定位不到,这种情况很有可能是frame在搞鬼. 进入到iframe <h ...

  7. 毛毛虫组【Beta】Scrum Meeting 1

    第一天 日期:2019/6/23 前言 第一次会议: 时间:6月20日 地点:教9-C404机房 内容:此次会议主要确定组内成员具体分工,并对目标进行了初步的确定. 1.1 今日完成任务情况以及遇到的 ...

  8. JS数据结构及算法(一) 堆栈

    最近在看<学习JavaScript数据结构与算法>这本书,感觉自己又涨知识了 哈哈... 现在将自己看的做个总结,也是巩固理解. 栈:先进后出,新添加和待删除的元素都保存在栈顶.可以用数组 ...

  9. 【交互 细节题 思维题】cf1064E. Dwarves, Hats and Extrasensory Abilities

    第一次做交互真有趣……:挺好的细节思维题 This is an interactive problem. In good old times dwarves tried to develop extr ...

  10. 896. Monotonic Array

    An array is monotonic if it is either monotone increasing or monotone decreasing. An array A is mono ...