原文:C#:foreach语句,yield语句

1. foreach语句

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

  1. foreach (Person p in persons)
  2. {
  3. Console.WriteLine(p);
  4. }

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

  • 调用GetEnumerator()方法,获得数组的一个枚举
  • 在while循环中,只要MoveNext()返回true,就一直循环下去
  • 用Current属性访问数组中的元素
  1. IEnumerator enumerator = persons. GetEnumerator();
  2. while (enumerator.MoveNext())
  3. {
  4. Person p = (Person) enumerator.Current;
  5. Console.WriteLine(p);
  6. }

2. yield语句

  • yield语句的两种形式:
  1. yield return <expression>;
  2. yield break;
  • 使用一个yield return语句返回集合的一个元素
  • 包含yield语句的方法或属性是迭代器。迭代器必须满足以下要求

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

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

  • yield return语句不能位于try-catch快。yield return语句可以位于try-finally的try块
  1. try
  2. {
  3. // ERROR: Cannot yield a value in the boday of a try block with a catch clause
  4. yield return "test";
  5. }
  6. catch
  7. { }
  8.  
  9. try
  10. {
  11. //
  12. yield return "test again";
  13. }
  14. finally
  15. { }
  16.  
  17. try
  18. { }
  19. finally
  20. {
  21. // ERROR: Cannot yield in the body of a finally clause
  22. yield return "";
  23. }
  • yield break语句可以位于try块或catch块,但是不能位于finally块

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

  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace ConsoleApplication6
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. HelloCollection helloCollection = new HelloCollection();
  11. foreach (string s in helloCollection)
  12. {
  13. Console.WriteLine(s);
  14. Console.ReadLine();
  15. }
  16. }
  17. }
  18.  
  19. public class HelloCollection
  20. {
  21.  
  22. public IEnumerator<String> GetEnumerator()
  23. {
  24. // yield return语句返回集合的一个元素,并移动到下一个元素上;yield break可以停止迭代
  25. yield return "Hello";
  26. yield return "World";
  27. }
  28. }
  29. }

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

  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. namespace ConsoleApplication8
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. MusicTitles titles = new MusicTitles();
  11. foreach (string title in titles)
  12. {
  13. Console.WriteLine(title);
  14. }
  15. Console.WriteLine();
  16.  
  17. foreach (string title in titles.Reverse())
  18. {
  19. Console.WriteLine(title);
  20. }
  21. Console.WriteLine();
  22.  
  23. foreach (string title in titles.Subset(, ))
  24. {
  25. Console.WriteLine(title);
  26. Console.ReadLine();
  27. }
  28. }
  29. }
  30.  
  31. public class MusicTitles
  32. {
  33. string[] names = { "a", "b", "c", "d" };
  34. public IEnumerator<string> GetEnumerator()
  35. {
  36. for (int i = ; i < ; i++)
  37. {
  38. yield return names[i];
  39. }
  40. }
  41.  
  42. public IEnumerable<string> Reverse()
  43. {
  44. for (int i = ; i >= ; i--)
  45. {
  46. yield return names[i];
  47. }
  48. }
  49.  
  50. public IEnumerable<string> Subset(int index, int length)
  51. {
  52. for (int i = index; i < index + length; i++)
  53. {
  54. yield return names[i];
  55. }
  56. }
  57. }
  58. }

输出:

C#:foreach语句,yield语句的更多相关文章

  1. C#-foreach与yield

    (转自:http://www.jb51.net/article/34627.htm) 1. foreach语句 C#编译器会把foreach语句转换为IEnumerable接口的方法和属性. fore ...

  2. C#中的foreach和yield

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

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

  4. yield语句

        自C#的第一个版本以来,使用foreach语句可以轻松地迭代集合.在C#1.0中,创建枚举器仍需要做大量的工作.C#2.0添加了yield语句,以便于创建枚举器.yield return语句返 ...

  5. python -迭代器与生成器 以及 iterable(可迭代对象)、yield语句

    我刚开始学习编程没多久,对于很多知识还完全不知道,而有些知道的也是一知半解,我想把学习到的知识记录下来,一是弥补记忆力差的毛病,二也是为了待以后知识能进一步理解透彻时再回来做一个补充. 参考链接: 完 ...

  6. Python生成器以及yield语句

    生成器是一种暂缓求值的技术,它可以用来生成一系列的值,但不会一次性生成所有的值,而只在需要的时候才计算和生成一个值. 通过yield语句构建生成器 要得到一个生成器,我们需要定义一个函数,这个函数返回 ...

  7. javascript笔记04:let语句 和 yield语句 和 with语句

    1.yield语句: <script type="application/javascript; version=1.7"> function generator() ...

  8. 生成器以及yield语句

    生成器以及yield语句最初的引入是为了让程序员可以更简单的编写用来产生值的序列的代码. 以前,要实现类似随机数生成器的东西,需要实现一个类或者一个模块,在生成数据的同时 保持对每次调用之间状态的跟踪 ...

  9. Python with yield语句

    1.with 语句 语法: with expression as variable 需要引入一个上下文管理协议,实现的方法是为一个类定义 __enter__() 和 __exit__() 方法, 在执 ...

随机推荐

  1. php实现数组中的逆序对(归并排序实现:排序 辅助数组)

    php实现数组中的逆序对(归并排序实现:排序 辅助数组) 一.总结 这题用归并排序  线段树   树状数组 等操作的复杂度应该都是小于n方的 二.php实现数组中的逆序对 题目描述 在数组中的两个数字 ...

  2. Android中的动画详解系列【1】——逐帧动画

    逐帧动画其实很简单,下面我们来看一个例子: <?xml version="1.0" encoding="utf-8"?> <animation ...

  3. SQL Server2008生成数据库字典

    1.我们在开发过程中可能会遇到这样的一种情况"当我们进行维护其他人的项目时或者项目的二次开发时可能会对原始的数据表进行分析",这里为大家介绍一种方便快捷生成数据库字典的方式. 我们 ...

  4. ES数据

    通过Elasticsearch使用的你的数据 Elasticsearch 系列导航 elasticsearch 与 elasticsearch-head 的安装 ElasticSearch Index ...

  5. 利用WPF建立自己的3d gis软件(非axhost方式)(十一)SDK中的动画系统

    原文:利用WPF建立自己的3d gis软件(非axhost方式)(十一)SDK中的动画系统 先下载SDK:https://pan.baidu.com/s/1M9kBS6ouUwLfrt0zV0bPew ...

  6. 利用WPF建立自己的3d gis软件(非axhost方式)(二)基础状态切换

    原文:利用WPF建立自己的3d gis软件(非axhost方式)(二)基础状态切换   先下载SDK:https://pan.baidu.com/s/1M9kBS6ouUwLfrt0zV0bPew 密 ...

  7. 【33.00%】【vijos P1002】过河

    描述 在河上有一座独木桥,一只青蛙想沿着独木桥从河的一侧跳到另一侧.在桥上有一些石子,青蛙很讨厌踩在这些石子上.由于桥的长度和青蛙一次跳过的距离都是正整数,我们可以把独木桥上青蛙可能到达的点看成数轴上 ...

  8. 保护SSD,设置Chrome浏览器临时文件夹到ramdisk分区

    很多用低端/山寨SSD的朋友都用Ramdisk来保护硬盘,一般都把系统temp目录和IE浏览器临时文件夹目录设到Ramdisk分区了.      最近用谷歌的chrome浏览器,发现浏览网页时候硬盘灯 ...

  9. Matlab Tricks(三十) —— 任意区间的均匀分布

    matlab 的内置函数 rand返回的是 0-1 区间上的均匀分布,rand的参数多是用于设置返回的矩阵的维度大小. 如果要得到 (a, b) 区间上的均匀分布,只需对其做简单的线性变换即可: a+ ...

  10. WSL探索及WSLAPI调用记录

    以前都是在虚拟机上安装linux,居然刚知道win10有WSL(Windows Subsystem for Linux)可以直接在win10上安装linux,消耗低,效率高,很赞,趁着干兴趣把WSL探 ...