背景
示例
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();
}
}
}
网友评论