C# - 委托

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace 委托2
 8 {
 9     class Program
10     {
11        /// <summary>
12        ///      声明委托: 委托的返回值类型、参数类型、参数个数必须与被委托函数保持一致。
13        /// </summary>
14         /// <param name="x"> 参与运算的数据 </param>
15         /// <param name="y"> 参与运算的数据 </param>
16        /// <returns></returns>
17         delegate double Calculate(double x, double y);
18         static void Main(string[] args)
19         {
20             Console.WriteLine( "委托: Add 运算结果: {0}", DoCal(Add, 5, 2) );
21             Console.WriteLine( "委托: Sub 运算结果: {0}", DoCal(Sub, 6, 3) );
22             Console.WriteLine( "委托: Mul 运算结果: {0}", DoCal(Mul, 10, 2) );
23             Console.WriteLine( "委托: Dev 运算结果: {0}", DoCal(Dev, 20, 2) );
24 
25             Console.ReadLine();
26         }
27 
28         /// <summary>
29         ///     执行运算
30         /// </summary>
31         /// <param name="cal"> 委托类型形参 </param>
32         /// <param name="x"> 参与运算的数据 </param>
33         /// <param name="y">参与运算的数据 </param>
34         /// <returns> 返回被委托函数的运算结果 </returns>
35         static double DoCal(Calculate cal, double x, double y)
36         {
37             return cal(x, y);
38         }
39         // 加法
40         static double Add(double x, double y)
41         {
42             return x + y;
43         }
44         // 减法
45         static double Sub(double x, double y)
46         {
47             return x - y;
48         }
49         // 乘法
50         static double Mul(double x, double y)
51         {
52             return x * y;
53         }
54         // 除法
55         static double Dev(double x, double y)
56         {
57             return x / y;
58         }
59 
60     }
61 }

 

posted @ 2016-04-02 10:36  C/C++/Python/Java  阅读(341)  评论(0编辑  收藏  举报