using System;
using System.Collections;
using System.Windows.Forms;
namespace 迭代器
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/*
迭代器可以返回相同类型的纸的有序序列的一段代码,可用做方法、运算或get访问
或get访问器的代码体。
yield return语句依次返回每个元素
yield break语句将终止迭代
返回类型必须为IEnumerable IEnumerator中任意一种
*/
public class Family : System.Collections.IEnumerable
{
string[] MyFamily = { "父母", "母亲", "弟弟", "妹妹" };
public IEnumerator GetEnumerator()
{
for (int i = 0; i < MyFamily.Length; i++)
{
yield return MyFamily[i];
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Family family = new Family();
foreach (string str in family)
{
richTextBox1.Text += str + "\n";
}
}
}
}
第二案例
using System;
using System.Collections;
namespace 作业1
{
class Program
{
static void Main(string[] args)
{
Year y = new Year();
foreach (string s in y)
{
Console.Write(s + " ");
}
Console.ReadLine();
}
}
public class Year : System.Collections.IEnumerable
{
string[] season = { "Spring", "Summer", "Autumn", "Winter" };
public IEnumerator GetEnumerator()
{
for (int i = 0; i < season.Length; i++)
{
yield return season[i];
}
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/107149.html