迭代器
迭代器是可以返回相同类型的值的有序序列的一段代码,可用作方法,运算符或get访问器的代码体.迭代器代码使用yield return语句依次返回每个元素,yield break语句将终止迭代.可以在类中实现多个迭代器,每个迭代器必须像类成员一样有唯一的名称,并且可以在foreach语句中被客户端代码调用.迭代器的返回类型必须为IEnumerrable或IEnumerator中的任意一种.
迭代器的使用
迭代器最常用的方法是对IEnumerator接口实现GetEnumrator方法
例
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 迭代器分部类
{
public class family : System.Collections.IEnumerable//创建family类继承IEnumerable接口
{
string[] a = { "父亲", "母亲", "哥哥" };
public System.Collections.IEnumerator GetEnumerator()//对IEnumerator接口实现GetEnumerator方法创建迭代器
{
for(int i = 0; i <= a.Length; i++)
{
yield return a[i];
}
}
}
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
family fa = new family();
foreach(string str in fa)
{
richTextBox1.Text += str + "\n"; }
}
}
}
分部类
分部类概述
分部类使程序的结构更加合理,代码组织更加严密.可以将类,结构和接口的定义拆分到两个或多个源文件中。每个源文件包含类定义的一部分,编译应用程序时,vs会把所有部分组合起来,这样的类称为分部类