迭代器的疑惑
public partial class Form2 : Form { public Form2() { InitializeComponent(); } private void Form2_Load(object sender, EventArgs e) { Family f = new Family(); foreach (var item in f) { richTextBox1.Text += item + "\n"; } //Test f = new Test(); //foreach (var item in f.GetEnumerator()) //{ // richTextBox1.Text += item + "\n"; //} } } public class Family : IEnumerable { string[] MyFamily = { "父亲", "母亲", "弟弟", "妹妹" }; string[] MyFamily1 = { "1", "2", "3", "4" }; public IEnumerator GetEnumerator() { for (int i = 0; i < MyFamily.Length; i++) { yield return MyFamily[i]; } } public IEnumerator GetEnumerator(int a) { for (int i = 0; i < MyFamily1.Length; i++) { yield return MyFamily1[i]; } } } public class Test { string[] MyFamily = { "父亲", "母亲", "弟弟", "妹妹" }; public string[] GetEnumerator() { return MyFamily; } } }
上面的代码会输出家庭成员在一个富文本框
我用Test方法也能实现,为啥要用迭代器,暂时还没想到哪里需要用到这个技术,可能以后就明白了。
提醒自己需要注意的是继承了IEnumerable接口后,必须实现GetEnumerator方法,我也试了用同样方法名不同参数的函数,foreach只会调用接口的方法(红色字体的方法)
今天周末又是无聊的一天!