首页 > 其他 > 详细

迭代器模式

时间:2017-06-04 18:05:04      阅读:263      评论:0      收藏:0      [点我收藏+]

C#中的IEnumerator实现了一个标准的iterator模式。

Iterator相当于collection对象的一个指针/游标/。

FQA

提问:迭代功能直接实现在Collection对象里可以吗?比如用索引下标的方式?

回答:可以,用索引来迭代也是一个好办法。但是这样一来,就不能同时对同一个collection进行迭代。要视情况而定用不用迭代模式。

把迭代器想象成一个指针,每一次迭代需要获取一个新的迭代器,不同的迭代的迭代器不能相互干扰。

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace IteratorSample
{
    class MyClass : IEnumerable
    {
        public IEnumerator GetEnumerator()
        {
            return new MyIterator(this);
        }
    }

    class MyIterator : IEnumerator
    {
        public MyIterator(MyClass myobject)
        {

        }

        public object Current 
        {
            get
            {
                return null;
            }
        }

        public bool MoveNext() 
        { 
            // todo 
            return true; 
        }

        public void Reset() { }
    }

    class Program
    {
        static void Main(string[] args)
        {
            // ddddd
            MyClass myobject = new MyClass();

            // method 1 to iterate the collectio object
            IEnumerator itor = myobject.GetEnumerator();

            while (itor.MoveNext())
            {
                Console.WriteLine(itor.Current);
            }

            // method 2 to iterate the collectio object
            foreach (var item in myobject)
            {
                Console.WriteLine(item);
            }
        }
    }
}

 

迭代器模式

原文:http://www.cnblogs.com/dirichlet/p/3276470.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!