实例一、 using System; namespace SimpleDelegate { //定义委托 delegate double DoubleOp(double x); class MainEntryPoint { static void Main() { //实例化 DoubleOp[] operations = { new DoubleOp(MathsOperations.MultiplyByTwo), new DoubleOp(MathsOperations.Square) }; /* 使用匿名方法 DoubleOp first = delegate(double value){return value * 2;}; DoubleOp second = delegate(double value) { return value * value; }; DoubleOp[] operations = { first, second }; */ //使用委托 for (int i = 0; i < operations.Length; i++) { Console.WriteLine("Using operations[{0}]:", i); ProcessAndDisplayNumber(operations[i], 2.0); ProcessAndDisplayNumber(operations[i], 7.94); ProcessAndDisplayNumber(operations[i], 1.414); Console.WriteLine(); } Console.ReadLine(); } static void ProcessAndDisplayNumber(DoubleOp action, double value) { double result = action(value); Console.WriteLine("Value is {0}, result of operation is {1}", value, result); } } class MathsOperations { public static double MultiplyByTwo(double value) { return value * 2; } public static double Square(double value) { return value * value; } } } 这段代码的关键一行是把委托传递给ProcessAndDisplayNumber()方法,例如:ProcessAndDisplayNumber(operations[i], 2.0); 其中传递了委托名,但不带任何参数,假定operations[i]是一个委托,其语法是: 1、operations[i]表示“这个委托”。换言之,就是委托代表的方法。 2、operations[i](2.0)表示“调用这个方法,参数放在括号中”。 实例二、 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)}; //实例化 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 { 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; } } } } } } 相关文章: