C#迭代器

本文详细介绍了C#中的迭代器功能,包括foreach的运行机制、传统集合遍历方式及使用迭代器简化遍历过程。通过实例展示了如何利用迭代器简化代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

摘要:迭代器是C#2.0中添加的功能,它能够使我们在类或结构中支持foreach迭代,而不必实现整个IEnumerable/IEnumerable接口。今天我们就一块看一下什么是c#中的迭代器吧。

主要内容:

1.foreach的运行机制

2.传统集合的遍历

3.使用迭代器

一、foreach的运行机制

我们在程序中经常会用到foreach,如果你把它理解成是for的一种简写形式的话那就太大材小用了,事实上foreach中包含了丰富的内容。我们知道要使用foreach遍历集合就必须实现IEnumerable接口,而要实现IEnumerable接口就要实现IEnumerator接口。关于如何实现这两个接口我们在第二部分会看到,在谈foreach的运行机制之前请允许我使用msdn中的Person类(我们下面的几部分中我们还会用到相关的People和PeopleEnum类):

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IteratorDemo { class Person { public Person(string fName, string lName) { this.firstName = fName; this.lastName = lName; } public string firstName; public string lastName; } }

当然具体细节我就不再说了,有了上面的Person类我们就可以运行下面的代码了:

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace IteratorDemo { class Program { static void Main(string[] args) { Person[] persons = new Person[] { new Person("Kenshin","Cui"), new Person("Miaoer","Sun"), new Person("Jinjuan","Shen"), new Person("Yanxin","Nie") }; foreach (Person p in persons) { Console.WriteLine(p.firstName + " " + p.lastName); } Console.Read(); } } }

具体的运行结果也没有什么可说的,可是为什么会有这样的结果呢?原因可以分两层来解释:第一就是我们的Persons是使用[]符号声明,这是一个Array类的记号。而Array类实现了IEnumerable接口中GetEnumerator()方法,因此它可以使用foreach进行迭代;第二,之所以实现IEnumerable接口的GetEnumerator()方法就能够迭代是因为foreach将上面的代码解析成如下的形式:

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace IteratorDemo { class Program { static void Main(string[] args) { Person[] persons = new Person[] { new Person("Kenshin","Cui"), new Person("Miaoer","Sun"), new Person("Jinjuan","Shen"), new Person("Yanxin","Nie") }; //等价的方法 IEnumerator enuerator = persons.GetEnumerator(); while (enuerator.MoveNext()) { Person p = enuerator.Current as Person; Console.WriteLine(p.firstName + " " + p.lastName); } Console.Read(); } } }

我们知道GetEnumerator()方法返回一个IEnumerator类型的接口,在IEnumerator接口中有一个Current属性来返回当前元素,而其MoveNext()方法又可以移动到集合的下一个元素(有则返回true,无则返回false),如此反复就形成了对整个集合的迭代(具体原理可以参见上面链接的内容)。

二、传统集合的遍历

上面我们谈到Array类实现了IEnumerable接口中的GetEnumerator()方法,因此可以使用foreach来循环遍历,那么我们自己当然也同样可以实现相关接口。

People类

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace IteratorDemo { class People:IEnumerable { private Person[] _people; public People(Person[] pArray) { _people = new Person[pArray.Length]; for (int i = 0; i < pArray.Length; i++) { _people[i] = pArray[i]; } } public IEnumerator GetEnumerator() { return new PeopleEnum(_people); } } }

PeopleEnum类

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace IteratorDemo { class PeopleEnum:IEnumerator { public Person[] _people; int position = -1; public PeopleEnum(Person[] list) { _people = list; } public bool MoveNext() { position++; return (position < _people.Length); } public void Reset() { position = -1; } public object Current { get { try { return _people[position]; } catch (IndexOutOfRangeException) { throw new InvalidOperationException(); } } } } }

在上面People类就实现了IEnumerable接口(当然截至到目前其相关内容也必须实现IEnumerator类),因此我们就可以遍历People类:

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace IteratorDemo { class Program { /* * 实现IEnumerable(显然目前我们必须先实现IEnumerator) */ static void Main(string[] args) { Person[] persons = new Person[] { new Person("Kenshin","Cui"), new Person("Miaoer","Sun"), new Person("Jinjuan","Shen"), new Person("Yanxin","Nie") }; People pe = new People(persons); foreach (Person p in pe) { Console.WriteLine(p.firstName + " " + p.lastName); } Console.Read(); } } }

三、使用迭代器

截止到现在我们可以看到如果让一个类或结构支持foreach就必须实现整个IEnumerable接口,这显然过于麻烦,毕竟我们不想在这方面花费太多的时间,那么此时我们就来使用迭代器吧。创建迭代器的最常用的方法就是对IEnumerable接口实现GetEnumerator()方法,例如将上面的People类可以写成这样:

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace IteratorDemo { class People:IEnumerable { private Person[] _people; public People(Person[] pArray) { _people = new Person[pArray.Length]; for (int i = 0; i < pArray.Length; i++) { _people[i] = pArray[i]; } } public IEnumerator GetEnumerator() { for (int i = 0; i < _people.Length; ++i) { yield return _people[i]; } } } }

从上面我们可以看到我们完全省略了创建PeopleEnum的过程(事实上我们还可以更简单,下面我们就可以看到,这里主要为了和上面的例子做个对比),当然这一切都归功于迭代器的功劳。迭代器使用yield return语句返回每个元素,yield break终止迭代(其返回类型必须为IEnumerable/IEnumerable、IEnumerator/Ienumerator类型)。yield关键字用于指定返回值,到达yield break时会保存当前位置,直到下次调用迭代器时将从此位置从新开始执行。当编译器见到迭代器时,会自动生成IEnumerable/IEnumerable接口的Current、MoveNext和Dispose方法。

当然可能有朋友到现在还有些模糊,那么您不妨简单的理解为:迭代器就是使用yield帮助我们省去了实现IEnumerator的麻烦(虽然,事实上远不止那么简单)。

之所以今天会想起这个话题,其实是因为偶然看到一段类似下面代码:

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace IteratorDemo { class Program { private static IList<Person> FilterPeople(IEnumerable<Person> people) { IList<Person> persons = new List<Person>(); foreach (Person p in people) { if (p.lastName == "Cui") { persons.Add(p); } } return persons; } static void Main(string[] args) { Person[] persons = new Person[] { new Person("Kenshin","Cui"), new Person("Miaoer","Sun"), new Person("Jinjuan","Shen"), new Person("Yanxin","Nie") }; foreach(Person p in FilterPeople(persons)) { Console.WriteLine(p.firstName + " " + p.lastName); } Console.Read(); } } }

想象一下如果使用迭代块(包含yield语句的方法或属性)会不会更优雅呢:

using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Text; namespace IteratorDemo { class Program { /* * 使用迭代快简化类似的方法 */ private static IEnumerable<Person> FilterPeople(IEnumerable<Person> people) { foreach(Person p in people) { if(p.lastName=="Cui") { yield return p; } } } static void Main(string[] args) { Person[] persons = new Person[] { new Person("Kenshin","Cui"), new Person("Miaoer","Sun"), new Person("Jinjuan","Shen"), new Person("Yanxin","Nie") }; foreach(Person p in FilterPeople(persons)) { Console.WriteLine(p.firstName + " " + p.lastName); } Console.Read(); } } }

知识共享许可协议
本作品 采用知识共享署名 2.5 中国大陆许可协议 进行许可,欢迎转载,演绎或用于商业目的。但转载请注明来自崔江涛(KenshinCui) ,并包含相关链接。

<think>好的,用户想了解C#迭代器的用法和相关编程问题。首先,我需要回忆C#迭代器的基本概念,并确保信息的准确性。迭代器C#中是通过yield return和yield break语句实现的,用于简化集合的遍历。需要解释什么是迭代器,以及它们如何工作。 接下来,我应该涵盖如何创建迭代器方法。可能需要举一个简单的例子,比如生成数字序列。同时,用户可能想知道如何实现自定义集合的迭代器,比如一个自定义类实现IEnumerable接口,使用迭代器块来返回元素。 然后,考虑用户可能遇到的常见问题,比如延迟执行特性。需要说明迭代器方法在调用时不会立即执行,而是在遍历时才会执行。这可能会导致一些意想不到的结果,比如在迭代过程中修改集合的影响。此外,异常处理也是需要注意的地方,在迭代器内部如何处理异常,以及finally块的行为。 另外,用户可能对实际应用场景感兴趣,比如分页处理大数据集,或者生成无限序列。这时候需要举出具体的例子,说明如何利用迭代器的延迟加载特性来优化性能。 还要记得引用提供的资料,比如引用[2]中提到foreach循环在不同语言中的应用,可以联系到C#中foreach如何与迭代器配合使用。引用[4]提到的MayExtensions和MayUtilities类可能涉及IEnumerable<T>的扩展方法,可以提到使用LINQ方法如Where、Select等与迭代器的结合。 需要检查是否有相关优化技巧,比如避免在迭代器中修改集合,或者使用yield break提前终止迭代。同时,性能方面的考虑,比如迭代器的内存效率和执行效率,尤其是在处理大规模数据时的优势。 最后,确保回答结构清晰,分点说明,并提供代码示例。可能的问题包括如何实现自定义迭代器、处理异常、性能优化等。生成的相关问题需要覆盖这些方面,帮助用户进一步学习。</think>### C#迭代器使用指南 迭代器C#中实现集合遍历的核心机制,通过`yield return`和`yield break`语句实现延迟执行特性[^2]。以下是具体用法和示例: #### 一、基础迭代器实现 1. **简单数字生成器** ```csharp public static IEnumerable<int> GenerateNumbers(int max) { for(int i=0; i<max; i++){ yield return i; // 每次迭代返回当前值 if(i > 5) yield break; // 提前终止迭代 } } // 使用示例 foreach(var num in GenerateNumbers(10)){ Console.WriteLine(num); // 输出0-6 } ``` 2. **自定义集合迭代** ```csharp public class ColorCollection : IEnumerable<string> { private string[] _colors = {"Red","Green","Blue"}; public IEnumerator<string> GetEnumerator() { foreach(var color in _colors){ yield return color; } } } ``` #### 二、高级应用场景 1. **分页处理大数据集** ```csharp public static IEnumerable<DataChunk> ReadLargeFile(string path) { using var reader = new StreamReader(path); while(!reader.EndOfStream){ var buffer = new char[1024]; reader.ReadBlock(buffer, 0, 1024); yield return new DataChunk(buffer); } } ``` 2. **无限序列生成** ```csharp public static IEnumerable<int> Fibonacci() { int a=0, b=1; while(true){ yield return a; (a, b) = (b, a+b); } } ``` #### 三、核心特性说明 1. **延迟执行机制**:迭代器方法在调用时仅返回枚举器对象,实际代码在`MoveNext()`时执行[^4] 2. **状态保持**:每次`yield return`会保留当前执行上下文状态 3. **异常处理**: ```csharp public static IEnumerable<string> SafeIteration() { try{ yield return "Start"; throw new Exception("Test"); } finally{ Console.WriteLine("Cleanup"); // 仍会执行 } } ``` #### 四、最佳实践建议 1. 避免在迭代过程中修改被遍历的集合 2. 复杂逻辑建议分离到单独方法 3. 结合LINQ使用提升效率: ```csharp var filtered = GenerateNumbers(100).Where(n => n%2 == 0); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值