namespace WinFormsApp4 { public partial class experiment : Form { public experiment() { InitializeComponent(); } int[] num = new int[10]; delegate bool Compare(int x, int y);//定义委托类型 void SortArray(Compare compare)//定义排序数组的方法 { for (int i = 0; i < num.Length; i++) for (int j = 0; j < i; j++) { if (compare(num[i], num[j]))//使用委托方法,比较两数大小. { int temp = num[i]; num[i] = num[j]; num[j] = temp; } } bool Ascending(int x, int y)//升序 { return x < y; } bool Descending(int x, int y)//降序 { return x > y; } public void display()//定义输出数组元素的方法 { txtTarget.Text = ""; foreach (int array in num) { txtTarget.Text += array + "\r\n"; } } } private void btnCreatArray_Click(object sender, EventArgs e) { txtSource.Text = string.Empty; Random rm = new Random(); for (int i = 0; i < num.Length; i++) { num[i] = rm.Next(10, 100); txtSource.Text += num[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(Descending)); display(); } } }
时间: 2024-02-10 18:16:01 浏览: 153
这段代码的问题在于 `Ascending` 和 `Descending` 方法定义在了 `SortArray` 方法内部,导致无法访问。同时, `display` 方法也定义在了 `SortArray` 方法内部,导致无法在其他方法中调用。
以下是优化后的代码,将 `Ascending`、`Descending` 和 `display` 方法提取到了类的外部,使其可以在其他方法中访问:
```csharp
namespace WinFormsApp4
{
public partial class experiment : Form
{
public experiment()
{
InitializeComponent();
}
int[] num = new int[10];
delegate bool Compare(int x, int y);
void SortArray(Compare compare)
{
for (int i = 0; i < num.Length; i++)
for (int j = 0; j < i; j++)
{
if (compare(num[i], num[j]))
{
int temp = num[i];
num[i] = num[j];
num[j] = temp;
}
}
}
bool Ascending(int x, int y)
{
return x < y;
}
bool Descending(int x, int y)
{
return x > y;
}
void Display()
{
txtTarget.Text = "";
foreach (int array in num)
{
txtTarget.Text += array + "\r\n";
}
}
private void btnCreatArray_Click(object sender, EventArgs e)
{
txtSource.Text = string.Empty;
Random rm = new Random();
for (int i = 0; i < num.Length; i++)
{
num[i] = rm.Next(10, 100);
txtSource.Text += num[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(Descending));
Display();
}
}
}
```
阅读全文