Form1.cs 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Drawing;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Forms;
  10. namespace WindowsFormsIEnumerator
  11. {
  12. public partial class Form1 : Form
  13. {
  14. public Form1()
  15. {
  16. InitializeComponent();
  17. }
  18. //创建迭代器,需要实现IEnumerable接口
  19. public class Family : System.Collections.IEnumerable
  20. {
  21. string[] MyFamily = { "父亲", "母亲", "弟弟", "妹妹" };
  22. public System.Collections.IEnumerator GetEnumerator()
  23. {
  24. //使用for依次返回数组或集合中的每一个元素
  25. for (int i = 0; i < MyFamily.Length; i++)
  26. {
  27. yield return MyFamily[i];
  28. }
  29. }
  30. }
  31. private void Form1_Load(object sender, EventArgs e)
  32. {
  33. //实例化迭代器
  34. Family myfamily = new Family();
  35. //遍历迭代器,相当于调用GetEnumerator()方法
  36. foreach (string str in myfamily)
  37. {
  38. richTextBox1.Text += str + "\n";
  39. }
  40. }
  41. }
  42. }