1. foreach

C#编译器会把foreach语句转换为IEnumerable接口的方法和属性。

foreach (Person p in persons)
{
Console.WriteLine(p);
}

foreach语句会解析为下面的代码段。

调用GetEnumerator()方法,获得数组的一个枚举

在while循环中,只要MoveNext()返回true,就一直循环下去

用Current属性访问数组中的元素

IEnumerator enumerator = persons. GetEnumerator();
while (enumerator.MoveNext())
{
Person p = (Person) enumerator.Current;
Console.WriteLine(p);
}

2. yield语句

yield语句的两种形式:

yield return <expression>;
yield break;

使用一个yield return语句返回集合的一个元素

包含yield语句的方法或属性是迭代器。迭代器必须满足以下要求

a. 返回类型必须是IEnumerableIEnumerable<T>IEnumeratorIEnumerator<T>

b. 它不能有任何ref或out参数

yield return语句不能位于try-catch快。yield return语句可以位于try-finally的try块

try
{
// ERROR: Cannot yield a value in the boday of a try block with a catch clause
yield return "test";
}
catch
{ } try
{
//
yield return "test again";
}
finally
{ } try
{ }
finally
{
// ERROR: Cannot yield in the body of a finally clause
yield return "";
}

yield break语句可以位于try块或catch块,但是不能位于finally块

下面的例子是用yield return语句实现一个简单集合的代码,以及用foreach语句迭代集合

using System;
using System.Collections.Generic; namespace ConsoleApplication6
{
class Program
{
static void Main(string[] args)
{
HelloCollection helloCollection = new HelloCollection();
foreach (string s in helloCollection)
{
Console.WriteLine(s);
Console.ReadLine();
}
}
} public class HelloCollection
{ public IEnumerator<String> GetEnumerator()
{
// yield return语句返回集合的一个元素,并移动到下一个元素上;yield break可以停止迭代
yield return "Hello";
yield return "World";
}
}
}

使用yield return语句实现以不同方式迭代集合的类:

using System;
using System.Collections.Generic; namespace ConsoleApplication8
{
class Program
{
static void Main(string[] args)
{
MusicTitles titles = new MusicTitles();
foreach (string title in titles)
{
Console.WriteLine(title);
}
Console.WriteLine(); foreach (string title in titles.Reverse())
{
Console.WriteLine(title);
}
Console.WriteLine(); foreach (string title in titles.Subset(, ))
{
Console.WriteLine(title);
Console.ReadLine();
}
}
} public class MusicTitles
{
string[] names = { "a", "b", "c", "d" };
public IEnumerator<string> GetEnumerator()
{
for (int i = ; i < ; i++)
{
yield return names[i];
}
} public IEnumerable<string> Reverse()
{
for (int i = ; i >= ; i--)
{
yield return names[i];
}
} public IEnumerable<string> Subset(int index, int length)
{
for (int i = index; i < index + length; i++)
{
yield return names[i];
}
}
}
}

以上动图由“图斗罗”提供

C#中的foreach和yield的更多相关文章

  1. .net 反射访问私有变量和私有方法 如何创建C# Closure ? C# 批量生成随机密码,必须包含数字和字母,并用加密算法加密 C#中的foreach和yield 数组为什么可以使用linq查询 C#中的 具名参数 和 可选参数 显示实现接口 异步CTP(Async CTP)为什么那样工作? C#多线程基础,适合新手了解 C#加快Bitmap的访问速度 C#实现对图片文件的压

    以下为本次实践代码: using System; using System.Collections.Generic; using System.ComponentModel; using System ...

  2. C#中的IEnumerator、foreach、yield

    [C#中的IEnumerator.foreach.yield] 1.IEnumerator,是一个接口,它的方法如下: 2.foreach语句,在编译后会变成IEnumerator的调用: 3.yie ...

  3. C#编程(三十五)----------foreach和yield

    枚举 在foreach语句中使用枚举,可以迭代集合中的元素,且无需知道集合中的元素个数. 数组或集合实现带GetEumerator()方法的IEumerable接口.GetEumerator()方法返 ...

  4. “mybatis 中使用foreach 传

    为了帮助网友解决“mybatis 中使用foreach 传”相关的问题,中国学网通过互联网对“mybatis 中使用foreach 传”相关的解决方案进行了整理,用户详细问题包括:mybatismap ...

  5. 【吐血推荐】简要分析unity3d中剪不断理还乱的yield

    在学习unity3d的时候很容易看到下面这个例子: void Start () { StartCoroutine(Destroy()); } IEnumerator Destroy(){ yield ...

  6. C#中的foreach语句与枚举器接口(IEnumerator)及其泛型 相关问题

    这个问题从<C#高级编程>数组一节中的foreach语句(6.7.2)发现的. 因为示例代码与之前的章节连贯,所以我修改了一下,把自定义类型改为了int int[] bs = { 2, 3 ...

  7. Unity 3D中不得不说的yield协程与消息传递

    1. 协程 在Unity 3D中,我们刚开始写脚本的时候肯定会遇到类似下面这样的需求:每隔3秒发射一个烟花.怪物死亡后20秒再复活之类的.刚开始的时候喜欢把这些东西都塞到Update里面去,就像下面这 ...

  8. 基于mysql对mybatis中的foreach进行深入研究

    鉴于上一篇博文一次修改mysql字段类型引发的技术探究提到的,要对foreach里面的collection相关的内容做一些介绍,今天就围绕foreach,做一些数据插入和查询相关的研究. 首先介绍一下 ...

  9. 在弹框中获取foreach中遍历的id值,并传递给地址栏(方法2)

    1.php有时候我们需要再弹框中获取foreach中遍历的数据(例如id),在弹框中点击按钮并传递给地址栏跳转.那么应该怎么做呢.第二种方法. 2. 可以在弹框中给出一个input hidden 点击 ...

随机推荐

  1. websocket echo test

    http://www.websocket.org/echo.html .net websocket server http://superwebsocket.codeplex.com/ http:// ...

  2. 【HDU-5246】超级赛亚ACMer(贪心)

    之前用了个nlogn的算法超时了.仅仅能改成n的算法了 大题贪心思路就是 对每一个人的能力值从小到大进行排序,当前能力值为now,那么我们找到一个人的能力使得这个能力值 <= now.now + ...

  3. 2. Add Two Numbers【medium】

    2. Add Two Numbers[medium] You are given two non-empty linked lists representing two non-negative in ...

  4. random实现验证码功能

    直接上代码: #-*- coding: utf-8 -*- #一个简单的验证码程序 import random #定义一个全局变量,初始值为空字符串 checkcode = '' for i in r ...

  5. 李洪强iOS开发之OC语言前期准备

    OC语言前期准备 一.OC简介 Oc语言在c语言的基础上,增加了一层最小的面向对象语法,完全兼容C语言,在OC代码中,可以混用c,甚至是c++代码. 可以使用OC开发mac osx平台和ios平台的应 ...

  6. java-SimpleDateFormatDemo & BirthDemo

    java日期格式设置,以及案例BirthDemo package com.example; import java.text.ParseException; import java.text.Simp ...

  7. Jetty锁定文件的问题

    在windows系统上,jetty默认在运行时会锁定部署的文件.这对于需要在程序运行期间动态生成或改动某些文件就变得不能执行!对于这一点,Jetty的官网上专门有文章进行了解释:http://docs ...

  8. redis主从备份

    redis主从备份,默认是读写分离的,master用于写,slave用于读.slave的写只能用于存储一些短暂状态的变量,应为在下次同步时,会被移除. 配置主从备份原则:配从不配主,既只需修改从库配置 ...

  9. ubuntu下telnet安装

    系统默认安装了telnet(client),所以只能用telnet登录别人开启telnet服务的主机,其他人是不能telnet登录本机的. 现在想要的是让别人可以使用telnet登录本机,需要安装两个 ...

  10. struts.xml文件:

    struts.xml文件中包含的配置信息,你将修改所采取的措施的开发.这个文件可以被用来覆盖默认设置的应用程序,例如struts.devMode=false和其他设置中定义的属性文件.这个文件可以创建 ...