C#2.0迭代器(转)

C#foreach语句常用来迭代可枚举的集合的元素。为了实现可枚举,一个集合必须有一个无参的GetEnumerator方法,这个方法返回一个枚举器。通常,枚举器比较难实现,但是,用迭代器来简化(枚举器)的任务十分有意义。

<?xml:namespace prefix = o />

一个迭代器是产生一个有序的值序列的一个语句块 。一个迭代器由出现一个或者多个yield语句而区别于一般的语句块:

·         Yield return 语句产生迭代的下一个值。

·         Yield break 语句指出这个迭代结束。

只要函数成员的返回类型是枚举器接口或者enumerable接口中的一个,那么一个迭代器就可以被用作函数成员体。

重要的是明白一个迭代器不是一种成员,而是一种实现函数成员的手段。一个通过迭代器实现的成员能被其他成员覆盖或者重载,而那些成员可能是迭代器实现的,也可能不是迭代器实现的。

以下的Stack<T>类使用迭代器实现它的GetEnumerator方法。迭代器自顶向下枚举栈里的元素。

using System.Collections.Generic;

class Stack<T> : IEnumerable<T>
    {
        T[] items ;
        int count ;
        public void Push(T data)
        {
           
            if (items == null)
            {

                items = new T[1];

            }
            else if (items.Length == count)
            {

                T[] newItems = new T[count * 2];

                Array.Copy(items, 0, newItems, 0, count);

                items = newItems;

            }

            items[count++] = data;
            
           

        }
        public T Pop()
        {
            T result = items[--count];

            items[count] = default(T);

            return result;

        }

 


        public IEnumerator<T> GetEnumerator()
        {
            for (int i = count - 1; i >= 0; i--)
            {
                yield return items[i];

            }
            //throw new Exception("The method or operation is not implemented.");
        }

 

        #region IEnumerable 成员

        IEnumerator IEnumerable.GetEnumerator()
        {
            throw new Exception("The method or operation is not implemented.");
        }

        #endregion
    }
GetEnumerator方法的出现使得Stack<T>成为一个可枚举类型,这允许Stack<T>的实例使用foreach语句。下面的例子将值0-9压入一个整数堆栈,然后用foreach循环按照从顶端到低端的顺序显示每一个值。

 class diedaiqi
    {
        static IEnumerable<int> FromTo(int from, int to)
        {

            while (from <= to) yield return from++;

        }

        static void Main()
        {
            
Stack<int> stack = new Stack<int>();

            for (int i = 0; i < 10; i++)
            {
                stack.Push(i);
            }

            foreach (int i in stack)
            {
                Console.Write("{0} ", i);
            }

            Console.WriteLine();

        }
    }

语句隐式地调用了集合的无参的GetEnumerator方法来得到一个枚举器。一个集合类中只能定义一个这样的无参的GetEnumerator方法,不过通常可以通过很多途径来实现枚举,包括使用参数来控制枚举。在这些情况下,一个集合可以使用迭代器来实现能够返回可枚举接口的属性和方法。例如,Stack<T>可以引入两个新属性;IEnumerable<T>类型的TopToBottom和BottomToTop
         public IEnumerable<T> TopToBottom
        {
            get
            {
                return this;
            }
        }

        public IEnumerable<T> BottomToTop
        {
            get
            {
                for (int i = 0; i < count; i++)
                {
                    yield return items[i];
                }
            }
        }
TopToBottom 属性的get访问器只是返回this因为栈自身是一个enumerableBottomToTop属性使用C#迭代器返回一个enumerable。以下的例子展示怎么使用属性以两种不同的顺序枚举元素:
            static void Main()
           {

               Stack<int> stack = new Stack<int>();
               for (int i = 0; i < 10; i++) stack.Push(i);
               foreach (int i in stack.TopToBottom) Console.Write("{0} ", i);
               Console.WriteLine();
               foreach (int i in stack.BottomToTop) Console.Write("{0} ", i);
               Console.WriteLine();
            }
当然,这些属性也能使用在foreach语句之外。以下例子传递调用属性的结果(作为参数)给(独立的)Print方法。这个例子还展示了一个迭代器用作为FromToBy方法体,接受参数。
class diedaiqi
    {

 

        static void Print(IEnumerable<int> collection)
        {
            foreach (int i in collection)
            {
                Console.Write("{0} ", i);
            }

            Console.WriteLine();
        }

        static IEnumerable<int> FromToBy(int from, int to, int by)
        {
            for (int i = from; i <= to; i+= by)
            {
                yield return i;
            }
        }

        static void Main()
        {

 

            Stack<int> stack = new Stack<int>();
            for (int i = 0; i < 10; i++) stack.Push(i);
            Print(stack.TopToBottom);
            Print(stack.BottomToTop);
            Print(FromToBy(10,20,2));

 

        }
    }

泛型和非泛型enumerable接口包含一个单独的成员,即一个不带任何参数GetEnumerator方法,这个方法返回一个枚举器接口。一个enumerable相当于一个枚举器工厂。当每次它们的GetEnumerator方法被调用,要适当地实现enumerables来获得独立的枚举器。假设enumerable的内状态在两次调用GetEnumerator没有变化,两个返回的枚举器应该产生以相同顺序排列的相同值集合。甚至枚举器的生存期以下面的代码实例交替, 这点也必须保持:

<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

None.gif using  System;
None.gif
using  System.Collections.Generic;
None.gif
class  Test
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif    
static IEnumerable<int> FromTo(int from, int to) dot.gif{
InBlock.gif        
while (from <= to) yield return from++;
ExpandedSubBlockEnd.gif    }

ExpandedSubBlockStart.gifContractedSubBlock.gif    
static void Main() dot.gif{
InBlock.gif        IEnumerable
<int> e = FromTo(110);
ExpandedSubBlockStart.gifContractedSubBlock.gif        
foreach (int x in e) dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif            
foreach (int y in e) dot.gif{
InBlock.gif                Console.Write(
"{0,3} ", x * y);
ExpandedSubBlockEnd.gif            }

InBlock.gif            Console.WriteLine();
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif


以上代码输出一个从整数110的简单的乘法表。注意FromTo方法只被调用一次来获取enumerable。然而e.GetEnumerator()被调用多次(被foreach语句)来获取多个等价枚举器。

这些枚举器都封装迭代器指定的代码在FromTo的声明里。注意迭代器代码修改了from参数。然而,枚举器独立运作,因为每个枚举器拥有了它自己的fromto参数的副本。在实现enumerables和枚举器时,枚举器之间的过渡状态的共享是应该被避免的一些细微的缺陷中的一个。C#迭代器被设计来帮助避免这些问题,(并且)以一种简单直观的方式实现健壮的枚举和枚举器。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值