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. verilog语法注意部分

    l generate语句 Verilog-2001添加了generate循环,允许产生module和primitive的多个实例化,同时也可以产生多个variable,net,task,functio ...

  2. awk按列求和

    awk 'BEGIN{total=0}{total+=$1}END{print total}'

  3. Python内置函数之chr()

    参数是一个整型对象: chr(integer) 返回整型对应的Unicode字符对象. 例子: >>> chr() '\x0c' >>> chr() 'ⲓ' > ...

  4. AutoLayout详解+手把手实战(转载)

    首先说一下这篇博客虽然是标记为原创,但是事实并非本人亲自写出来的,知识点和例子本人花了一天各处查 找和整理最终决定写一个汇总的详解,解去各位朋友到处盲目查找的必要,因为不是转载某一个人的内容,故此不标 ...

  5. scp命令的用法

    用法: scp 命令 scp 能够在 2个 linux 主机间拷贝文件: 命令基本格式: scp [可选參数] file_source file_target ====== 从 本地 拷贝到 远程 拷 ...

  6. MapReduce源码分析之Task中关于对应TaskAttempt存储Map方案的一些思考

    我们知道,MapReduce有三层调度模型,即Job——>Task——>TaskAttempt,并且: 1.通常一个Job存在多个Task,这些Task总共有Map Task和Redcue ...

  7. 22lvs 健康节点检查

    [root@lb03 scripts]# cat lvm_health_check.sh #!/bin/bash web_ip=( 10.0.0.17 10.0.0.18 ) # 检查恢复就添加节点 ...

  8. 【Python + ATX基于uiaotumator2】之Android—APP自动化简易例子

    上代码: import uiautomator2 as u2 from time import sleep d = u2.connect_usb('608ad0fe') #打开小卖 # d(text= ...

  9. Spring 核心组件工作原理简析

    Spring Framework 的核心组件有三个: Spring Core,Spring Context 和 Spring Beans,它们奠定了 Spring 的基础并撑起了 Spring 的框架 ...

  10. 解决xshell6评估过期,需采购问题

    2018年12月20日补充 绿色免安装版: https://www.lanzous.com/i2njdre 密码:9b7t 2018年7月18日补充 感谢s***5大佬提供注册包,有需要的小伙伴,请留 ...