C#——设计窗体程序,随机生成1-100之间的10个数字,并通过委托实现剩下或降序排列

1.设计界面

C#——设计窗体程序,随机生成1-100之间的10个数字,并通过委托实现剩下或降序排列_第1张图片

2.编写代码

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Linq;

using System.Text;

using System.Windows.Forms;

 

namespace 随机数委托排序

{

    public partial class Form1 : Form

    {

        public Form1()

        {

            InitializeComponent();

        }

 

        int[] a = new int[10];

        delegate bool Compare(int x, int y);

        void SortArray(Compare compare)

        {

            for (int i = 0; i < a.Length; i++)

            {

                for (int j = 0; j <= i; j++)

                {

                    if(compare (a[i],a[j]))

                    {

                        int t = a[i];

                        a[i] = a[j];

                        a[j] = t;

                    }

                }

            }

        }

            bool Ascending(int x,int y)//比较x是否小于y

            {

                return x

            }

            bool Desecding(int x,int y)

            {

                return x>y;

            }

        void display()

        {

            textBox2.Text ="";

            foreach(int i in a)

            {

                textBox2.Text +=i+ "\r\n";

            }

        }

 

        //生成数组

        private void button1_Click(object sender, EventArgs e)

        {

            textBox1.Text = "";

            textBox2.Text = "";

            Random r=new Random();

            for(int i=0;i

            {

                a[i] = r.Next(100);//取0-100间的随机数

                textBox1.Text += a[i] + "\r\n";

            }

        }

 

        //升序排序

        private void button2_Click(object sender, EventArgs e)

        {

            //SortArray(new Compare(Ascending));//实参是新建的委托对象

            Compare c = new Compare(Ascending);

            SortArray(c);

            display();

        }

 

        //降序排序

        private void button3_Click(object sender, EventArgs e)

        {

            SortArray(new Compare(Desecding));

            display();

        }

 

    }

}

 

3.运行结果

C#——设计窗体程序,随机生成1-100之间的10个数字,并通过委托实现剩下或降序排列_第2张图片

你可能感兴趣的:(C#——设计窗体程序,随机生成1-100之间的10个数字,并通过委托实现剩下或降序排列)