网摘 |  收藏 | 

C#中使用Iterator

转自http://blog.163.com/ketai_lin/blog/static/235906782007384917627/

初步研究,抛砖引玉。

Iterator是Visual C# 2005的新功能,Iterator可以让您支持类或结构中的Foreach循环反复运算,而不需要实现整个IEnumerable接口,只要指定好Iterator就可以。当编译器侦测到您的Iterator时,它会自动产生IEnumerable接口的Current MoveNextDispose方法。Iterator特别适合与集合类搭配使用,因为能够提供逐一查看像是二元树等复杂数据结构的方法。

Yield关键字可以用来指定返回的值。在Iterator区块中,可以提供运算结果值给枚举值对象或表示反复运算。当到达Yield return语句时,便会保存目前的位置,每次连续逐一查看Foreach循环,或直接调用IEnumerator.MoveNext方法时,下一个Iterator程序代码主体会从前一个Yield语句之后继续执行,并一直重复,直到Iterator主体结束或遇到Yield break语句为止。

  Iterator的程序代码区段,会返回特定类型的按顺序排列的值,可以当做方法主体,运算符或属性中的Get访问函数使用,您可以在类上实现多个Iterator。请记住,每个Iterator必须像任何类成员一样拥有唯一名称,由Foreach语句中的程序代码调用,同时Iterator的返回类型必须是IEnumerableIEnumerator接口。

  创建Iterator最常见的方式就是,实现IEnumerable接口的GetEnumerator方法,加入GetEnumerator方法会使类型变成可枚举的类型,并允许使用Foreach语句。

例如:

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

namespace Iterrator
{
    public class SampleCollection
    {
        private int[] _items;
        public SampleCollection()
        {
            _items = new int[5] { 5, 6, 3, 7, 9 };
        }

        public System.Collections.IEnumerable BuildCollection()
        {
            for (int i = 0; i < _items.Length; i++)
            {
                yield return _items[i];
                yield return _items[i] * 100;
            }
        }
    }
}

以上定义一个类,下面在一个窗口中调用。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Iterrator
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            SampleCollection collections = new SampleCollection();
            foreach (int i in collections.BuildCollection())
            {
                MessageBox.Show("在类中成员元素的数值是:"+ i.ToString() +" ");
            }
        }
    }
}
posted @ 2012-11-21 17:39  xulonghua219  阅读(3365)  评论(0编辑  收藏  举报