C#-foreach与yield
(转自: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的更多相关文章
- C#中的IEnumerator、foreach、yield
[C#中的IEnumerator.foreach.yield] 1.IEnumerator,是一个接口,它的方法如下: 2.foreach语句,在编译后会变成IEnumerator的调用: 3.yie ...
- 字典查找、linq、foreach、yield等几种查找性能对比
先上代码,以1千万记录的内存查找测试: List<Student> stuList = new List<Student>(); Dictionary<int, Stud ...
- C#编程(三十五)----------foreach和yield
枚举 在foreach语句中使用枚举,可以迭代集合中的元素,且无需知道集合中的元素个数. 数组或集合实现带GetEumerator()方法的IEumerable接口.GetEumerator()方法返 ...
- C#中的foreach和yield
1. foreach C#编译器会把foreach语句转换为IEnumerable接口的方法和属性. foreach (Person p in persons) { Console.WriteLine ...
- .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 ...
- C# ~ 从 IEnumerable / IEnumerator 到 IEnumerable<T> / IEnumerator<T> 到 yield
IEnumerable / IEnumerator 首先,IEnumerable / IEnumerator 接口定义如下: public interface IEnumerable /// 可枚举接 ...
- 初来乍到 Java 和 .Net 迭代器功能
最近有一个需求是这样的, 根据键值对存储类型数据,也算是数据缓存块模块功能设计. 一个键对应多个值.每一个键的值类型相同,但是每个不同的键之间类型不一定相同. Java 设计如下 HashMap< ...
- 【译】.NET Core 3.0 中的新变化
.NET Core 3.0 是 .NET Core 平台的下一主要版本.本文回顾了 .Net Core 发展历史,并展示了它是如何从基本支持 Web 和数据工作负载的版本 1,发展成为能够运行 Web ...
- .Net Core3 新特性/新功能 16条
.net core 3实现了.net 标准2.1. 1.生成可执行文件 以前版本需要dotnet run运行项目,.net core 3支持直接生成目标平台的可执行文件.比如windows就是exe了 ...
随机推荐
- DRF(4) - 认证、权限组件
一.引入 通过前面三节课的学习,我们已经详细了解了DRF提供的几个重要的工具,DRF充分利用了面向对象编程的思想,对Django的View类进行了继承,并封装了其as_view方法和dispatch方 ...
- struts 多文件上传 xml 版本
[本文简介] 本文将介绍 以配置 struts.xml 的方式 实现 多文件上传的功能. [文件夹结构] [struts.xml] <?xml version="1.0" ...
- C/C++中的输出对齐设置
输出对齐有两个方面,一是输出宽度,一是左对齐还是又对齐. 在C++里面,默认是右对齐,可以通过cout.setf(std::ios::left)调整为左对齐,而且这种调整是全局的 ,一次设置,后面都有 ...
- xlrd、xlwt操作execl表格
在python中操作execl进行数据读写的时候,可以使用xlrd进行文件的读取,使用xlwt将数据写入execl中. 1.xlrd xlwt用来读取execl中的数据,常见的用法如下. (1)打开e ...
- Python(变量、数据类型)
常量:python中没有常量,只能通过名字特征来提示例如:全部大写,如 : OLDBOY_AGE=57 一.变量 变量声明变量#!/usr/bin/env python age=18gender1=' ...
- Django框架之模板基础,静态文件配置
一.模板继承 目的是:减少代码的冗余 语法: {% block classinfo %} {% endblock %} 具体步骤: 1.创建一个base.html文件,2.把要显示的页面的内容写在这里 ...
- JVM内存杂记1
大多数 JVM 将内存区域划分为 Method Area(Non-Heap)(方法区) ,Heap(堆) , Program Counter Register(程序计数器) , VM Stack( ...
- 数据结构&算法(二)_算法基础之前传(递归、时间复杂度、空间复杂度、二分查找)
什么是算法: 间而言之算法(Algorithm):一个计算过程,解决问题的方法 递归的两个特点: 调用自身 结束条件 递归示例: def func(x): : print("我的小鲤鱼&qu ...
- alias指令别名和 sshpass命令简化ssh登陆
在之前的一篇博文中 ubuntu下关于profile和bashrc中环境变量的理解 提到过可以编辑bashrc文件,vim ~/.bashrc,来编写自己的小指令,就是给长指令取个简单的别名.比如b ...
- mfc学习---文档视图架构
MFC的AppWizard可以生成三种类型的应用程序:基于对话框的应用.单文档应用(SDI)和多文档应用(MDI). 一般情况下,采用文档/视结构的应用程序至少应由以下对象组成: 1. ...