C#中迭代器和分部类的使用

 更新时间:2024年01月22日 10:26:53   作者:wenchm  
迭代器和分部类是C#语言的两种重要特性,本文主要介绍了C#中迭代器和分部类的使用,具有一定的参考价值,感兴趣的可以了解一下

迭代器在集合类中经常使用,而分部类则提供了一种将一个类分成多个类的方法,这对于有大量代码的类非常实用。

一、迭代器

迭代器是可以返回相同类型的值的有序序列的一段代码,可用作方法、运算符或get访问器的代码体。迭代器代码使用yield return语句依次返回每个元素,yield break语句将终止迭代。可以在类中实现多个迭代器,每个迭代器都必须像任何类成员一样有唯一的名称,并且可以在foreach语句中被客户端代码调用。迭代器的返回类型必须为IEnumerable或IEnumerator中的任意一种。 

创建迭代器最常用的方法是对IEnumerator接口实现GetEnumerator()方法。

1.示例源码

示例迭代器的用法:Windows应用创建一个名为Family的类并继承IEnumerable接口,对 IEnumerator接口实现GetEnumerator()方法创建迭代器。最后遍历输出Family类中的内容。

//迭代器
using System.Collections;
namespace _01
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            groupBox1.Text = "测试迭代器";

            Family myfamily = new();            //实例化Family
            foreach (string str in myfamily)    //遍历输出myfamily
            {
                richTextBox1.Text += str + "\n";
            }
        }

        /// <summary>
        /// 创建一个名为Family的类,其继承IEnumerable接口,
        /// 该接口公开枚举数,该枚举数支持在非泛型集合上进行简单迭代。
        /// 对IEnumerator接口实现GetEnumerator()方法创建迭代器
        /// </summary>
        public class Family : IEnumerable
        {
            readonly string[] MyFamily = { "父亲", "母亲", "弟弟", "妹妹" };
            public IEnumerator GetEnumerator()
            {
                for (int i = 0; i < MyFamily.Length; i++)
                {
                    yield return MyFamily[i];   //迭代器返回数组元素
                }
            }
        }
    }
}

2.生成效果:

 

请读者思考一下:迭代器的返回值去了哪里?Form1_Load事件是如何获得数据的呢?这个问题的答案才是迭代器知识点的精华。

二、分部类

分部类使程序的结构更加合理,代码的组织更加紧密。可以将类、结构或接口的定义拆分到两个或多个源文件中。每个源文件包含类定义的一部分,编译应用程序时,VS会把所有部分组合起来,这样的类被称为分部类。

 分部类主要应用在以下方面:

  • 当项目比较庞大时,使用分部类可以拆分一个类至几个文件中,这样的处理可以使不同的开发人员同时进行工 作,避免了效率的低下。
  • 使用自动生成的源时,无须重新创建源文件即可将代码添加到类中。VS在创建Windows窗体和Web服务包装代码等 时都使用此方法。开发人员无须编辑VS所创建的文件,即可创建使用这些类的代码。

定义分部类时需要使用partial关键字,分部类的每个部分都必须包含一个partial关键字,并且其声明必须与其他部分位于同一命名空间。开发分部类时,要成为同一类型的各个部分的所有分部类型定义都必须在同一程序集或同一模块(.exe或.dll文件)中进行定义,分部类定义不能跨越多个模块。

1.示例源码

//分部类
namespace _02
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            groupBox1.Text = "四则运算:";
            button1.Text = "等于";
            label1.Text= "运算结果:";
                    
            label1.AutoSize = true;
            button1.Size = new Size(65, 23);
            textBox1.Size = new Size(75, 23);
            textBox2.Size = new Size(70, 23);
            textBox3.Size = new Size(205, 23);
            comboBox1.Size = new Size(35, 23);

            comboBox1.Items.AddRange(["加", "减", "乘", "除"]);
            comboBox1.SelectedIndex = 0;
            comboBox1.DropDownStyle = ComboBoxStyle.DropDownList;           
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            try
            {
                Account at = new();
                int M = int.Parse(textBox1.Text.Trim());    //操作数1
                int N = int.Parse(textBox2.Text.Trim());    //操作数2
                string str = comboBox1.Text;
                switch (str)
                {
                    case "加": textBox3.Text = Account.Addition(M, N).ToString(); break;
                    case "减": textBox3.Text = Account.Subtration(M, N).ToString(); break;
                    case "乘": textBox3.Text = Account.Multiplication(M, N).ToString(); break;
                    case "除": textBox3.Text = Account.Division(M, N).ToString(); break;
                }
            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        #region 加减乘除
        partial class Account							    //分部类第1部分
        {
            public static int Addition(int a, int b)       
            {
                return (a + b);							    //加法
            }
        }
        partial class Account								//分部类第2部分
        {
            public static int Multiplication(int a, int b)	
            {
                return (a * b);								//乘法
            }
        }
        partial class Account                               //分部类第3部分
        {
            public static int Subtration(int a, int b)      
            {
                return (a - b);                             //减法
            }
        }
        partial class Account                               //分部类第4部分
        {
            public static double Division(int a, int b)
            {                
                return ((double)a / b);                     //除法
            }
        }
        #endregion 加减乘除
    }
}

2.生成效果

到此这篇关于C#中迭代器和分部类的使用的文章就介绍到这了,更多相关C# 迭代器和分部类内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家! 

您可能感兴趣的文章:

相关文章

最新评论