委托就像一個函數的指針,在程式運作時可以使用它們來調用不同的函數。委托存儲方法名,以及傳回值類型和參數清單。一個委派有兩個部分:委派類和類的委派對象。
定義委派類,如 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 }