c#委托实例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
|
// 委托使用例子 // 节选自《C#入门经典》 using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace weituo { class Program { static void Main( string [] args) { // 声明委托变量 ProcessDelegate process; Console.WriteLine( "请输入用逗号分隔的两个数字:" ); string input = Console.ReadLine(); int commaPos = input.IndexOf( ',' ); double param1 = Convert.ToDouble(input.Substring(0, commaPos)); double param2 = Convert.ToDouble(input.Substring(commaPos + 1,input.Length - commaPos -1)); Console.WriteLine( "输入M乘法D除法" ); input =Console.ReadLine(); // 初始化委托变量 if (input == "M" ) process = new ProcessDelegate(Multiply); //注释:此处也可以写process = Multiply else process = new ProcessDelegate(Divide); // 使用委托调用函数 double result = process(param1,param2); Console.WriteLine( "结果:{0}" ,result); Console.ReadKey(); } // 声明委托 delegate double ProcessDelegate( double param1, double param2); static double Multiply( double param1, double param2) { return param1 * param2; } static double Divide( double param1, double param2) { return param1 / param2; } } } |