通过使用 Delegate 类,委托实例可以封装属于可调用实体的方法。
对于实例方法,委托由一个包含类的实例和该实例上的方法组成。
对于静态方法,可调用实体由一个类和该类上的静态方法组成。
因此,委托可用于调用任何对象的函数,而且委托是面向对象的、类型安全的。
定义和使用委托有三个步骤:
声明
实例化
调用
C#可通过使用委托来确定在运行时选择要调用哪些函数。
以下代码演示了委托的创建、实例化和调用: C# 复制代码 public class MathClass { public static long Add(int i, int j) // static { return (i + j); } public static long Multiply (int i, int j) // static { return (i * j); } } class TestMathClass { delegate long Del(int i, int j); // declare the delegate type static void Main() { Del operation; // declare the delegate variable operation = MathClass.Add; // set the delegate to refer to the Add method long sum = operation(11, 22); // use the delegate to call the Add method operation = MathClass.Multiply; // change the delegate to refer to the Multiply method long product = operation(30, 40); // use the delegate to call the Multiply method System.Console.WriteLine("11 + 22 = " + sum); System.Console.WriteLine("30 * 40 = " + product); } } 输出 11 + 22 = 33 30 * 40 = 1200