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. docker下部署spring boot

    第 5 章 Docker + Spring Boot: 快速搭建和部署Java Web应用 0.你需要: JDK 1.8 : java -version Maven 3.0+ : mvn -v Git ...

  2. 在CTreeCtrl控件点击事件中获取点击的项

    网上搜了一下,有两种方法: 1.使用GetSelectedItem() HTREEITEM hItem = m_treeCtrl.GetSelectedItem(); CString strText ...

  3. c++ using Handle Class Pattern to accomplish implementation hiding

    Reference material: Thinking In C++ 2nd eidition chapter 5 section "Handle classes" If the ...

  4. 深入Redis漏斗限流

    漏斗限流是最常用的限流方法之一,漏斗流水的速率大于灌水的速率,漏斗就永远装不满,反之水就会溢出. 所以漏斗的剩余空间就代表当前行为可以持续进行的数量,水流出的速率代表系统允许该行为的最大频率. imp ...

  5. Spring MVC复选框(多项)

    以下示例显示如何在使用Spring Web MVC框架的表单中使用多个复选框(Checkbox).首先使用Eclipse IDE来创建一个WEB工程,并按照以下步骤使用Spring Web Frame ...

  6. OpenCV学习笔记廿一:opencv_contrib模块

    一,简介: 该库为新加入代码库的算法.

  7. 有关于iOS字体的设置

    1.网上搜索字体文件(后缀名为.ttf,或.odf) 2.把字体库导入到工程的resouce中 3.在程序viewdidload中加载一下一段代码 NSArray *familyNames = [UI ...

  8. Python 使用MySQL

    在导入MySQLdb之前,需要安装MySQLdb模块.使用pip安装,命令如下: pip install MySQL-python 安装成功后,导入MySQLdb模块 import MySQLdb 连 ...

  9. 如何停止和扭转UIView的动画

    本文转载至  http://codego.net/576089/ 我有它收缩时碰到切换按钮UIView的动画跳和它扩展恢复到原来的大小当再次接触到按钮.密封式前大灯一切都工作得很好.问题是,动画师注意 ...

  10. 用javascript复制富文本

    由于项目需求,希望能够用javascript复制富文本格式的数据,例如全选一个网页Ctrl+C, Ctrl+V到一个word文档中,数据还是原来的格式,显示出来的样子也都和原来一样.现在希望使用jav ...