C# 迭代器模式通俗解析
迭代器模式就像是一个智能书架管理员,它能按顺序把书架上的书一本本拿给你,而你不需要知道书架是怎么排列的,也不需知道书的具体存放方式。
举个现实生活例子
想象你去图书馆找编程书籍:
- 你不需要知道图书馆如何存储这些书(数组?链表?数据库?)
- 你只需要对图书管理员说"下一本"
- 管理员会按一定顺序把书递给你
- 你可以在任何时候说"够了"停止获取
迭代器模式正是提供了这种"顺序访问集合元素而不暴露内部结构"的能力。
C#代码实现示例
C#已经内置了迭代器模式的实现(IEnumerable
和IEnumerator
接口),我们来看如何自定义:
// 1. 自定义集合类
public class BookShelf : IEnumerable<Book>
{
private Book[] _books;
private int _last = 0;
public BookShelf(int capacity)
{
_books = new Book[capacity];
}
public void AddBook(Book book)
{
if (_last < _books.Length)
{
_books[_last++] = book;
}
else
{
Console.WriteLine("书架已满!");
}
}
// 实现GetEnumerator方法(C#内置迭代器支持)
public IEnumerator<Book> GetEnumerator()
{
for (int i = 0; i < _last; i++)
{
yield return _books[i]; // yield关键字简化迭代器实现
}
}
// 显式接口实现
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
// 2. 元素类
public class Book
{
public string Title { get; }
public string Author { get; }
public Book(string title, string author)
{
Title = title;
Author = author;
}
public override string ToString() => $"{Title}(作者:{Author})";
}
// 3. 使用迭代器
class Program
{
static void Main(string[] args)
{
var shelf = new BookShelf(4);
shelf.AddBook(new Book("C#入门经典", "John Smith"));
shelf.AddBook(new Book("设计模式之美", "李智慧"));
shelf.AddBook(new Book("算法导论", "Thomas Cormen"));
shelf.AddBook(new Book("重构", "Martin Fowler"));
Console.WriteLine("书架上的书:");
// 使用foreach遍历(背后就是迭代器模式)
foreach (var book in shelf) // 这里隐式调用了GetEnumerator()
{
Console.WriteLine(" " + book);
}
// 等价于以下显式使用迭代器的代码:
Console.WriteLine("\n显式使用迭代器:");
using (var iter = shelf.GetEnumerator())
{