C#:foreach与yield语句的介绍_C#教程

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];
             }
         }
     }
 }

输出:

时间: 2024-09-19 08:16:57

C#:foreach与yield语句的介绍_C#教程的相关文章

C#的WebBrowser的操作与注意事项介绍_C#教程

1.在Winform里使用WebBrowser,要对Form1.cs添加一些东西:    1.1 在"public partial class Form1 : Form"上方,添加: 复制代码 代码如下: [PermissionSet(SecurityAction.Demand, Name = "FullTrust")][System.Runtime.InteropServices.ComVisibleAttribute(true)]    1.2 在Form1的S

C# LINQ to XML应用介绍_C#教程

W3C制定了XML DOM标准,.Net为了支持W3C的标准,从1.1版本开始就引入了XmlDocument类.我在前一篇博客中,介绍了如何使用XmlDocument类来对XML文档进行操作.后来 .Net又引入了LINQ,于是LINQ to XML也就应运而生,所以在.Net中,不仅可以用W3C XML DOM标准,还可以使用LINQ to XML来操作XML文档.下面就来简单介绍一下如何使用LINQ to XML. (一) 加载 加载XML比较常用的有三种方法: 复制代码 代码如下: pub

ADO.NET实体数据模型详细介绍_C#教程

OleDbConnection,OracleConnection 或者SqlConnection这种连接,直接执行sql语句.现在的连接方式执行sql语句有了很大的不同,下面先看看简单的单表的增删改查操作,然后再看多表的关联查询,带参数查询等.一.ADO.NET Entity对单表的增删改查有一个表,即在工程中是一个实体user,为了测试方便,所有字段为string型. 1.增加新记录增加一条记录如下: [csharp] using (OracleEntities entities = new

C#读写操作app.config中的数据应用介绍_C#教程

读语句: 复制代码 代码如下: String str = ConfigurationManager.AppSettings["DemoKey"]; 写语句: 复制代码 代码如下: Configuration cfa = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 2 cfa.AppSettings.Settings["DemoKey"].Value = "D

DataReader、DataSet、DataAdapter和DataView使用介绍_C#教程

ADO.NET提供两个对象用于检索关系型数据并把它存储在内存中,分别是DataSet和DataReader.DataSet提供内存中关系数据的表现--包括表和次序.约束等表间的关系的完整数据集合.DataReader提供快速.只向前.只读的来自数据库的数据流. 使用DataSet时,一般使用DataAdapter(也可能是CommandBuilder)与数据源交互,用DataView对DataSet中的数据进行排序和过滤.DataSet可以被继承来建立强化类型的DataSet,用于暴露表.行.列

C# 泛型深入理解介绍_C#教程

引言: 在上一个专题中介绍了C#2.0 中引入泛型的原因以及有了泛型后所带来的好处,然而上一专题相当于是介绍了泛型的一些基本知识的,对于泛型的性能为什么会比非泛型的性能高却没有给出理由,所以在这个专题就中将会介绍原因和一些关于泛型的其他知识. 一.泛型类型和类型参数 泛型类型和其他int,string一样都是一种类型,泛型类型有两种表现形式的:泛型类型(包括类.接口.委托和结构,但是没有泛型枚举的)和泛型方法.那什么样的类.接口.委托和方法才称作泛型类型的呢 ?我的理解是类.接口.委托.结构或方

C# 写入XML文档三种方法详细介绍_C#教程

我在以前的博客中介绍了如何使用XmlDocument类对XML进行操作,以及如何使用LINQ to XML对XML进行操作.它们分别使用了XmlDocument类和XDocument类.在本文中,我再介绍一个类,XmlTextWriter.我们分别用这三个类将同样的xml内容写入文档,看一看哪种写法最直观.简便. 我们要写入的XML文档内容为 复制代码 代码如下: <?xml version="1.0" encoding="UTF-8"?> <Co

C#使用foreach循环遍历数组完整实例_C#教程

本文实例讲述了C#使用foreach循环遍历数组的方法.分享给大家供大家参考,具体如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace ConsoleApplication1 { class Program { static void Main(string[] args) { //声明数组. 第一种方法. 声明并分配元素大小. int[] Myint

C#基础知识之base关键字介绍_C#教程

一.调用基类已被派生类重写的方法 复制代码 代码如下: public class Father {     public virtual void Say()     {         Console.WriteLine("Father Say");     } }   public class Son : Father {     public override void Say()     {         base.Say();         Console.WriteLi