C#-从入门到精通-第18章 迭代器和分部类

【迭代器】
迭代器代码使用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);
        }
}

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一个喜欢弹吉他的程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值