C#设计模式--迭代器模式

C# 迭代器模式通俗解析

迭代器模式就像是一个智能书架管理员,它能按顺序把书架上的书一本本拿给你,而你不需要知道书架是怎么排列的,也不需知道书的具体存放方式。

举个现实生活例子

想象你去图书馆找编程书籍:

  • 你不需要知道图书馆如何存储这些书(数组?链表?数据库?)
  • 你只需要对图书管理员说"下一本"
  • 管理员会按一定顺序把书递给你
  • 你可以在任何时候说"够了"停止获取

迭代器模式正是提供了这种"顺序访问集合元素而不暴露内部结构"的能力。

C#代码实现示例

C#已经内置了迭代器模式的实现(IEnumerableIEnumerator接口),我们来看如何自定义:

 
// 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())
        {
            
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值