委托就像一个函数的指针,在程序运行时可以使用它们来调用不同的函数。委托存储方法名,以及返回值类型和参数列表。一个委派有两个部分:委派类和类的委派对象。
定义委派类,如 public delegate double DelegateCalculation(
double acceleration ,double time
);
然后可以创建一个委派对象
DelegateCalculation myDelegateCalculation =
new DelegateCalculation(MotionCalculations.FinalSpeed);
例如:
1 /*
2 Example12_1.cs illustrates the use of a delegate
3 */
4
5 using System;
6
7
8 // declare the DelegateCalculation delegate class
9 public delegate double DelegateCalculation(
10 double acceleration, double time
11 );
12
13
14 // declare the MotionCalculations class
15 public class MotionCalculations
16 {
17
18 // FinalSpeed() calculates the final speed
19 public static double FinalSpeed(
20 double acceleration, double time
21 )
22 {
23 double finalSpeed = acceleration * time;
24 return finalSpeed;
25 }
26
27 // Distance() calculates the distance traveled
28 public static double Distance(
29 double acceleration, double time
30 )
31 {
32 double distance = acceleration * Math.Pow(time, 2) / 2;
33 return distance;
34 }
35
36 }
37
38
39 class Example12_1
40 {
41
42 public static void Main()
43 {
44
45 // declare and initialize the acceleration and time
46 double acceleration = 10; // meters per second per second
47 double time = 5; // seconds
48 Console.WriteLine("acceleration = " + acceleration +
49 " meters per second per second");
50 Console.WriteLine("time = " + time + " seconds");
51
52 // create a delegate object that calls
53 // MotionCalculations.FinalSpeed
54 DelegateCalculation myDelegateCalculation =
55 new DelegateCalculation(MotionCalculations.FinalSpeed);
56
57 // calculate and display the final speed
58 double finalSpeed = myDelegateCalculation(acceleration, time);
59 Console.WriteLine("finalSpeed = " + finalSpeed +
60 " meters per second");
61
62 // set the delegate method to MotionCalculations.Distance
63 myDelegateCalculation =
64 new DelegateCalculation(MotionCalculations.Distance);
65
66 // calculate and display the distance traveled
67 double distance = myDelegateCalculation(acceleration, time);
68 Console.WriteLine("distance = " + distance + " meters");
69
70 }
71
72 }