概念
委托
其实是一种引用方法的类型。一旦为委托分配了方法,委托将与该方法具有完全相同的行为,就像C++中的函数指针一样。委托方法的使用可以像其他任何方法一样,具有参数和返回值。
背景
首先来一段代码,来个简单的冒泡排序
public void BubbleSort(int[] array)
{
//冒泡排序
for (int i = array.Length - 1; i >= 0; i--)
{
for (int j = 1; j <= i; j++)
{
if (array[j - 1] > array[j])
{
int temp = array[j - 1];
array[j - 1] = array[j];
array[j] = temp;
}
}
}
}
这个方法是用来对数据进行升序排序的,为了能方便的选择升序、降序或者字典序来排序,下面我们来通过委托来实现这个功能。
委托的简单使用
委托的声明,委托声明决定了可由该委托引用的方法。委托可指向一个与其具有相同标签的方法。
public delegate bool CompareHandler(int first, int second);
上面的委托可被用于引用任何一个带有两个int参数的方法,并返回一个bool类型变量。
声明与委托CompareHandler兼容的方法,这个方法应该是两个整型的参数,并返回bool值
//字典序排序 public static bool AlphabeticalCompare(int a, int b) { int cmp = a.ToString().CompareTo(b.ToString()); return cmp > 0; }
带有委托参数的排序方法
public static void BubbleSort(int[] array, CompareHandler compareMethod) { for (int i = array.Length - 1; i >= 0; i--) { for (int j = 1; j <= i; j++) { //调用委托方法比较 if (compareMethod(array[j - 1], array[j])) { int temp = array[j - 1]; array[j - 1] = array[j]; array[j] = temp; } } } }
委托方法的调用
BubbleSort(array, AlphabeticalCompare);
CompareHandler委托是引用类型,C#2.0之后不必用new实例化,但C#1.0中的委托实例化是这样的:
BubbleSort(array, new CompareHandler(AlphabeticalCompare));
整体代码
class Program
{
//声明委托
public delegate bool CompareHandler(int first, int second);
private static void Main(string[] args)
{
int[] array = new[] { 23, 11, 2, 1, 9, 4, 3, 10, 5, 8 };
Console.WriteLine("升序:");
BubbleSort(array, GreaterThan);
foreach (int item in array)
{
Console.Write(item + " ");
}
Console.WriteLine();
Console.WriteLine("字典序升序:");
BubbleSort(array, AlphabeticalCompare);
foreach (int item in array)
{
Console.Write(item + " ");
}
}
public static void BubbleSort(int[] array)
{
//...
}
public static void BubbleSort(int[] array, CompareHandler compareMethod)
{
//...
}
//声明委托方法
public static bool GreaterThan(int a, int b)
{
//...
}
//字典序排序
public static bool AlphabeticalCompare(int a, int b)
{
//...
}
}