迭代器可以使开发人员方便的使用foreach语句访问类中的字段值,而分布类使程序的结构更加灵活,协同工作更加方便。
迭代器
迭代器使用yield return 语句依此返回每个元素,yield break语句将终止迭代,可以在类中实现多个迭代器,每个迭代器必须像任何类成员一样有唯一名称,并且可以在foreach语句中被客户端代码调用。
常用方法:对IEnumerator接口实现GetEnumerator方法。
public class Family:System.Collections.IEnumerable//类继承IEnumerable接口
{
string[] MyFamily={"爸爸","妈妈","弟弟","妹妹"};
public System.Collections.IEnumerator GetEnumerator()
{
for(int i=0;i<MyFamily.Length;i++)
{
yield return MyFamily[i];
}
}
}
class Program
{
static void Main(string[] args)
{
Family family=new Family();
foreach(string str in family)
{
//
}
}
}
分部类
分部类可以将类、结构或接口的定义拆分到2个或多个源文件中,这样处理可以使不同的开发人员同时进行工作。
定义分部类时需要使用partial关键字,分部类的每个部分都必须包含一个partial关键字。并且分部类的声明必须与其他部分位于同一命名空间。开发分布类时,要成为同一类型的各个部分的所有分部类型定义必须在同一程序集或同一模块中定义。
举例
private void button1_Click(object sender, EventArgs e)
{
try
{
account at = new account();//实例化分部类
int M = int.Parse(textBox1.Text.Trim());
int N = int.Parse(textBox2.Text.Trim());
string str = comboBox1.Text;
switch(str)
{
case "加":
textBox3.Text = at.addition(M, N).ToString(); break;
case "减":
textBox3.Text = at.substration(M, N).ToString(); break;
case "乘":
textBox3.Text = at.multiplication(M, N).ToString(); break;
case "除":
textBox3.Text = at.division(M, N).ToString(); break;
}
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
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 substration(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.Items.Add("加");
comboBox1.Items.Add("乘");
comboBox1.Items.Add("减");
comboBox1.Items.Add("除");
comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;
}
在设置分部类时,各个部分必须具有相同的可访问性,如public,private等。
来源:CSDN
作者:分享让世界更好
链接:https://blog.csdn.net/weixin_42974146/article/details/103200956