C#迭代器的基本應用

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

namespace WindowsFormsApplication2
{
    //迭代器可以返回相同類型的值的有序序列的一段代碼,
    //可以用作方法,運算符,get訪問器的代碼體。
    //IEnumerable公開枚舉數,該枚舉數支持在非泛型集合上進行簡單迭代
    //迭代器的返回類型必須爲IEnumerable和IEnumerator的一種
    public class Family:System.Collections.IEnumerable//迭代器最常用的方法是對IEnumerable接口實現GetEnumerable()方法
    {
        string[] MyFamily = { "父親", "母親", "妹妹" };
        public System .Collections.IEnumerator GetEnumerator()
        {
            for (int i=0;i<MyFamily.Length; i++)
            {
                yield return MyFamily[i];//迭代器代碼使用yield return依次返回每個元素。
                //yield return 終止迭代。
            }
        }
       
    }
   
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            Family myfamily = new Family();
            foreach (string str in myfamily)
            {
                richTextBox1.Text += str + "\n";
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章