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的实例详解的细致内容,更多请关注ki4网别的相干文章!