美文网首页
设计模式 - 迭代器模式

设计模式 - 迭代器模式

作者: Mitchell | 来源:发表于2016-07-10 22:40 被阅读60次
  • 迭代器模式,提供一种方法顺序访问一个聚合对象中各个元素,二又不暴露该对象的内部表示。
public interface IEnumerator
{
    object Current
    {
        get;
    }
    bool MoveNext();
    void Reset();
}
public interface IEnumerable
{
    IEnumerator GetEnumerator();
}
static void Main(string[] args)
{
    IList<string>a = new List<string>();
    a.Add("1");
    a.Add("2");
    a.Add("3");
    a.Add("4");
    a.Add("5");
    foreach(string item in a){
        Console.WriteLine("{0}请买车票!",item);
    }
    Console.Read();
}

foreach 所做的事情:

IEnumerator<string> e = a.GetEnumerator();
while(e.MoveNext())
{
    Console.WriteLine("{0}请买车票!",e.Current);
}

相关文章

网友评论

      本文标题:设计模式 - 迭代器模式

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