(转自:http://www.jb51.net/article/34627.htm)

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. 返回类型必须是IEnumerable、IEnumerable<T>、IEnumerator或 IEnumerator<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(2, 2))
{
Console.WriteLine(title);
Console.ReadLine();
}
}
} public class MusicTitles
{
string[] names = { "a", "b", "c", "d" };
public IEnumerator<string> GetEnumerator()
{
for (int i = 0; i < 4; i++)
{
yield return names[i];
}
} public IEnumerable<string> Reverse()
{
for (int i = 3; i >= 0; 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. C#中的IEnumerator、foreach、yield

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

  2. 字典查找、linq、foreach、yield等几种查找性能对比

    先上代码,以1千万记录的内存查找测试: List<Student> stuList = new List<Student>(); Dictionary<int, Stud ...

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

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

  4. C#中的foreach和yield

    1. foreach C#编译器会把foreach语句转换为IEnumerable接口的方法和属性. foreach (Person p in persons) { Console.WriteLine ...

  5. .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 ...

  6. C# ~ 从 IEnumerable / IEnumerator 到 IEnumerable<T> / IEnumerator<T> 到 yield

    IEnumerable / IEnumerator 首先,IEnumerable / IEnumerator 接口定义如下: public interface IEnumerable /// 可枚举接 ...

  7. 初来乍到 Java 和 .Net 迭代器功能

    最近有一个需求是这样的, 根据键值对存储类型数据,也算是数据缓存块模块功能设计. 一个键对应多个值.每一个键的值类型相同,但是每个不同的键之间类型不一定相同. Java 设计如下 HashMap< ...

  8. 【译】.NET Core 3.0 中的新变化

    .NET Core 3.0 是 .NET Core 平台的下一主要版本.本文回顾了 .Net Core 发展历史,并展示了它是如何从基本支持 Web 和数据工作负载的版本 1,发展成为能够运行 Web ...

  9. .Net Core3 新特性/新功能 16条

    .net core 3实现了.net 标准2.1. 1.生成可执行文件 以前版本需要dotnet run运行项目,.net core 3支持直接生成目标平台的可执行文件.比如windows就是exe了 ...

随机推荐

  1. Django框架--路由分配系统

    Python的WEB框架有Django.Tornado.Flask 等多种,Django相较与其他WEB框架其优势为:大而全,框架本身集成了ORM.模型绑定.模板引擎.缓存.Session等诸多功能. ...

  2. Django:学习笔记(1)——开发环境配置

    Django:学习笔记(1)——开发环境配置 Django的安装与配置 安装Django 首先,我们可以执行python -m django --version命令,查看是否已安装django. 如果 ...

  3. display:inline与display:block——行内元素显示与块级元素显示

    display:inline 的作用是设置对象做为行内元素显示,inline是内联对象的默认值(ps:内联对象就是不自动产生换行的元素,比如span) 而我们一般用的div是块级元素,默认displa ...

  4. maven入门学习(一)

    一.maven介绍 1.软件开发中我们为什么要使用maven呢?(纯属个人体会观点,如有错误,敬请指正) (1)其一,企业岗位需求,目前的IT开发招聘岗位上,基本都要求会使用maven.        ...

  5. Django学习笔记之Django模版系统

    官方文档 常用语法 只需要记两种特殊符号: {{  }}和 {% %} 变量相关的用{{}},逻辑相关的用{%%}. 变量 {{ 变量名 }} 变量名由字母数字和下划线组成. 点(.)在模板语言中有特 ...

  6. Sybase:存储过程中采用临时表存储统计数据

    Sybase:存储过程中采用临时表存储统计数据 作用 很有效的提升统计查询速度,对于数据量亿级.千万级多表之间关联查询,非常有效: 使用 --无需定义临时表,直接使用 --自动释放临时表 select ...

  7. web页面如何打包封闭成手机APP

    所谓的webApp就是html页面跟原生app结合而成的一种应用,这种应用的开发可以节省不少的成本,做出来的app跟原生一样,webApp利用框架技术可以让你有使用app的感觉,具体可以看平安银行的a ...

  8. ixgbe RSS原理分析

    这个月,一直在搞ixgbe RSS,希望能使得收包均衡,结果没成功,但是对网卡的收包原理理解得更深入些. 1.网卡硬件通过网线或者光纤收包. 2.网卡的RSS功能根据网络五元组计算得到32bit的ha ...

  9. Logstash过滤器修改数据

    数据修改(Mutate) filters/mutate 插件是 Logstash 另一个重要插件.它提供了丰富的基础类型数据处理能力.包括类型转换,字符串处理和字段处理等. 类型转换 类型转换是 fi ...

  10. Flume-NG中的Channel与Transaction关系(原创)

    在sink和source中(不管是内置还是自定义的),基本都有如下代码,这些代码在sink中的process方法中,而在source中自己不需要去写,在source中getChannelProcess ...