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. iphone开发思维导图

  2. ABAP,Java和JavaScript的序列化,反序列化

    ABAP 1. ABAP提供了一个工具类cl_proxy_xml_transform,通过它的两个方法abap_to_xml_xstring和xml_xstring_to_abap实现两种格式的互换. ...

  3. noip模拟赛#14

    #14: T1:f[x]=x-1(x&1)||x/2(x&1=0) 求[n,m]有多少个数可以通过变换得到k.(1e9). =>好像cf上看过类似的题,用二进制的方式来写.不过我 ...

  4. 【转】Deactivating your reflector

    原文:http://blog.csdn.net/cxwl3sxl/article/details/8072195 背景: 因为想破解一个.net写的程序,需要在visual studio 2010中使 ...

  5. npm模块安装机制简介

    npm是node的模块管理器,功能及其强大,它是node获得成功的重要原因之一. 正因为有了nom,我们只要一行命令,就能安装别人写好的模块. $ npm install 本文介绍npm模块安装机制的 ...

  6. openstack nova fail to create vm

    2019-05-13 14:43:27.017 47547 ERROR nova.compute.manager [req-3f1af0ed-c342-4cf3-8e76-6963053a5227 8 ...

  7. Maven各种常用架包配置文件,保存一份

    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/20 ...

  8. ssh整合思想 Spring与Hibernate和Struts2的action整合 调用action添加数据库 使用HibernateTemplate的save(entity)方法 update delete get 等方法crud操作

    UserAction类代码: package com.swift.action; import com.opensymphony.xwork2.ActionSupport; import com.sw ...

  9. ES6学习总结 (二)

    一:ES6为函数做了哪些扩展 参数的默认值 传统写法: function person(n,a){ var name =n || "zhangsan"; var age = a | ...

  10. 分享几个能用的 editplus 注册码

    转载自: https://www.cnblogs.com/shihaiming/p/6422441.html 原文:http://host.zzidc.com/wljc/1286.html EditP ...