using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace 委托与事件处理_c_____
{
//委托最常见的用法就是用作回调执行所需任务的方法
//想创建委托,只需使用关键字new创建一个委托类型的新实例,将方法名称作为参数传递即可
//声明委托实例:public delegate void OpDelegate(...)
public class BubbleSort
{
//例子。对数组冒泡排序,比较方法为委托,在类外定义
public delegate bool Order(object first, object second);
public void Sort(Array table, Order sortHandler)
{
if(sortHandler == null)
throw new ArgumentNullException();
bool nothingSwapped = false;
int pass = 1;
while(nothingSwapped == false)
{
nothingSwapped = true;
for(int index = 0;index < table.Length-pass;++index)
{
//用一个 Order 委托确认排序顺序
if (sortHandler(table.GetValue(index),
table.GetValue(index + 1)) == false)
{
nothingSwapped = false;
object temp = table.GetValue(index);
table.SetValue(table.GetValue(index + 1), index);
table.SetValue(temp, index + 1);
}
}
++pass;
}
}
}
}
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace 委托与事件处理_c_____ { class DelegateSortApp { static int[] sortTable = { 5, 4, 6, 8, 2 }; static void Main(String[] args) { DelegateSortApp app = new DelegateSortApp(); //按原来顺序打印数组 foreach (int i in sortTable) Console.WriteLine(i); Console.WriteLine("Sorting"); BubbleSort sorter = new BubbleSort();//创建 BubbleSort.Order order = new BubbleSort.Order(SortOrder);//写入委托 sorter.Sort(sortTable, order);//这里调用到委托 foreach (int i in sortTable) Console.WriteLine("Done"); } //委托方法,由用户自己实现 static public bool SortOrder(object first, object second) { int f = (int)first; int s = (int)second; return f < s; } } } 委托:很好的封装了类,将具体的实现交给用户,对于类的设计很有用。接下来将讨论事件