美文网首页
{C#}设计模式辨析.迭代器

{C#}设计模式辨析.迭代器

作者: 码农猫爸 | 来源:发表于2021-08-10 08:30 被阅读0次

    背景

    • 隐藏遍历方法,确保foreach的实现

    示例

    using System.Collections;
    using System.Collections.Generic;
    using static System.Console;
    
    namespace DesignPattern_Enumerator
    {
        // 逆向迭代器类,指定遍历方法
        public class ReversedIterator : IEnumerator
        {
            private readonly Aggregate aggregate;
            private int current;
    
            public ReversedIterator(Aggregate aggregate)
            {
                this.aggregate = aggregate;
                Reset();
            }
    
            // 调用前,先MoveNext()
            public object Current => aggregate.All[current];
    
            public bool MoveNext()
            {
                if (current == 0) return false;
    
                current--;
                return true;
            }
    
            public void Reset() => current = aggregate.All.Count;
        }
    
        // 集合类,IEnumerable仅包含IEnumerator
        public class Aggregate : IEnumerable
        {
            public List<string> collection = new List<string>();
    
            // foreach必须实现IEnumerator
            public IEnumerator GetEnumerator()
                => new ReversedIterator(this);
    
            public void Add(string item) => collection.Add(item);
    
            public List<string> All => collection;
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                var alphabets = new Aggregate();
                alphabets.Add("a");
                alphabets.Add("b");
                alphabets.Add("c");
    
                foreach (var alphabet in alphabets)
                {
                    WriteLine(alphabet);
                }
    
                ReadKey();
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:{C#}设计模式辨析.迭代器

          本文链接:https://www.haomeiwen.com/subject/dhnzvltx.html