using System; namespace BubbleSorter ... { delegate bool CompareOp(object lhs, object rhs); class MainEntryPoint ...{ static void Main() ...{ Employee[] employees = ...{ new Employee("Bugs Bunny", 20000), new Employee("Elmer Fudd", 10000), new Employee("Daffy Duck", 25000), new Employee("Wiley Coyote", (decimal)1000000.38), new Employee("Foghorn Leghorn", 23000), new Employee("RoadRunner'", 50000) }; /**//*将委托实例化并且初始化,这里和类的操作是一样的但是当创建委托时, * 创建与类 Employee 上的静态方法 RhsIsGreater 关联的新的委托对象。 * 在两个例子中,新的委托对象都立即传递给 Sort 方法。 * 传递给 new 表达式的参数很特殊:它的编写类似于方法调用,但没有方法的参数。 */ CompareOp employeeCompareOp = new CompareOp(Employee.RhsIsGreater); BubbleSorter.Sort(employees, employeeCompareOp); for (int i = 0; i < employees.Length; i++) Console.WriteLine(employees[i].ToString()); Console.ReadLine(); } } class Employee // : object ...{ private string name; private decimal salary; public Employee(string name, decimal salary) ...{ this.name = name; this.salary = salary; } public override string ToString() ...{ return string.Format(name + ", {0:C}", salary); } //第二个参数大于第一个参数的时候返回真,否则返回假 public static bool RhsIsGreater(object lhs, object rhs) ...{ Employee empLhs = (Employee) lhs; Employee empRhs = (Employee) rhs; return (empRhs.salary > empLhs.salary) ? true : false; } } //定义个一冒泡排序的类 class BubbleSorter ...{ static public void Sort(object [] sortArray, CompareOp gtMethod) ...{ for (int i=0 ; i<sortArray.Length ; i++) ...{ for (int j=i+1 ; j<sortArray.Length ; j++) ...{ //不能直接进行对动态的值(运行过程中确定的值)比较,采用委托方法 if (gtMethod(sortArray[j], sortArray[i])) ...{ object temp = sortArray[i]; sortArray[i] = sortArray[j]; sortArray[j] = temp; } } } } }}