- 切换到源代码编辑视图,在窗体类中定义委托、排序的方法,代码如下:
int[] a = new int[10];
delegate bool Compare(int x, int y); //声明委托类型
void SortArray(Compare compare) //委托形参
{
for (int i = 1; i < a.Length; i++)
for (int j = 0; j < a.Length-1; j++)
if (compare(a[j], a[j+1])) //使用委托调用方法,以比较大小
{
int t = a[j];a[j] = a[j+1];a[j+1] = t;
}
}
bool Ascending(int x, int y) //比较x是否大于y
{
return x > y;
}
bool Desecding(int x, int y) //比较x是否小于y
{
return x < y;
}
void display() //输出数组
{
txtTarget.Text = "";
foreach (int i in a)
{
txtTarget.Text += i + "\r\n";
}
}
- 编写按钮的 Click 事件方法,代码如下:
private void btnCreateArray_Click(object sender, EventArgs e)
{
txtSource.Text = "";
txtTarget.Text = "";
Random r = new Random();
for (int i = 0; i < a.Length; i++)
{
a[i] = r.Next(100); //取0~100间的随机数
txtSource.Text += a[i] + "\r\n";
}
}
private void btnAscSort_Click(object sender, EventArgs e)
{
SortArray(new Compare(Ascending)); 实参是新创建的委托对象
display();
}
private void btnDescSort_Click(object sender, EventArgs e)
{
SortArray(new Compare(Desecding)); //实参是新创建的委托对象
display();
具体代码如下:
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 form
{
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 = 1; i < a.Length; i++)
for (int j = 0; j < a.Length - 1; j++)
if (compare(a[j], a[j + 1])) //使用委托调用方法,以比较大小
{
int t = a[j]; a[j] = a[j + 1]; a[j + 1] = t;
}
}
bool Ascending(int x, int y) //比较x是否大于y
{
return x > y;
}
bool Desecding(int x, int y) //比较x是否小于y
{
return x < y;
}
void display() //输出数组
{
txtTarget.Text = "";
foreach (int i in a)
{
txtTarget.Text += i + "\r\n";
}
}
private void btnCreateArray_Click(object sender, EventArgs e)
{
txtSource.Text = "";
txtTarget.Text = "";
Random r = new Random();
for (int i = 0; i < a.Length; i++)
{
a[i] = r.Next(100); //取0~100间的随机数
txtSource.Text += a[i] + "\r\n";
}
}
private void btnAscSort_Click(object sender, EventArgs e)
{
SortArray(new Compare(Ascending)); 实参是新创建的委托对象
display();
}
private void btnDescSort_Click(object sender, EventArgs e)
{
SortArray(new Compare(Desecding)); //实参是新创建的委托对象
display();
}
}
}
运行效果图如下: