【迭代器】
迭代器代码使用yield return语句依次返回每个元素,yield break语句终止迭代。迭代器的返回类型必须为IEnumerable或IEnumerator中的一种。
创建迭代器最常用的方法时对IEnumerable接口实现GetEnumerator方法。
public class Family : System.Collections.IEnumerable//继承IEnumerable接口
{
string[] MyFamily ={ "父亲","母亲","弟弟","妹妹"};
//对IEnumerable接口实现GetEnumerator方法。
public System.Collections.IEnumerator GetEnumerator()
{
for (int i = 0; i < MyFamily.Length; i++)
{
yield return MyFamily[i];//使用yield return语句返回每个元素
}
}
}
private void Form1_Load(object sender, EventArgs e)
{
Family myfamily = new Family();
foreach (string str in myfamily)
{
richTextBox1.Text += str + "\n";
}
}
【分部类】
使用partial关键字
partial class account//分部类第一部分
{
public int addition(int a, int b)//创建一个整型方法
{
return a + b;//方法中的加法运算
}
}
partial class account//分部类第二部分
{
public int multiplication(int a, int b)//创建一个整型方法
{
return a * b;//方法中的乘法运算
}
}
partial class account//减法
{
public int subtration(int a,int b)
{
return a-b;
}
}
partial class account //除法
{
public int division(int a, int b)
{
return a / b;
}
}
private void Form1_Load(object sender, EventArgs e)
{
comboBox1.SelectedIndex = 0;//设置控件选择第一项
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;//显示为下拉列表的样式
}
private void button1_Click(object sender, EventArgs e)
{
try
{
account at = new account();//实例化分部类
int M = int.Parse(txtNo1.Text.Trim());//获取文本框中的值
int N = int.Parse(txtNo2.Text.Trim());
string str = comboBox1.Text;
switch (str)
{
case "加": txtResult.Text = at.addition(M, N).ToString(); break;
case "减": txtResult.Text = at.subtration(M, N).ToString(); break;
case "乘": txtResult.Text = at.multiplication(M, N).ToString(); break;
case "除": txtResult.Text = at.division(M, N).ToString(); break;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}