using System; 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 WindowsFormsIEnumerator { public partial class Form1 : Form { public Form1() { InitializeComponent(); } //创建迭代器,需要实现IEnumerable接口 public class Family : System.Collections.IEnumerable { string[] MyFamily = { "父亲", "母亲", "弟弟", "妹妹" }; public System.Collections.IEnumerator GetEnumerator() { //使用for依次返回数组或集合中的每一个元素 for (int i = 0; i < MyFamily.Length; i++) { yield return MyFamily[i]; } } } private void Form1_Load(object sender, EventArgs e) { //实例化迭代器 Family myfamily = new Family(); //遍历迭代器,相当于调用GetEnumerator()方法 foreach (string str in myfamily) { richTextBox1.Text += str + "\n"; } } } }