C#的delegate与C的函数指针

引子:

一个小示例,希望可以帮助广大侠士们来理解delegate。

在C中的函数指针示例:

 1      #include <stdio.h>
 2   
 3       // 减法运算
 4       int minus(int a, int b) {
 5           return a - b;
 6       }
 7   
 8       // 加法运算
 9       int sum(int a, int b) {
10          return a + b;
11      }
12  
13      // 这个counting函数是用来做a和b之间的计算,至于做加法还是减法运算,由函数的第1个参数决定
14      void counting( int (*p)(int, int) , int a, int b) {
15          int result = p(a, b);
16          printf("计算结果为:%d\n", result);
17      }
18  
19      int main()
20      {
21          // 进行加法运算
22          counting(sum, 6, 4);
23          
24          // 进行减法运算
25          counting(minus, 6, 4);
26          
27          return 0;
28      }

本代码引自:http://www.cnblogs.com/mjios/archive/2013/03/19/2967037.html

此页有详细的关于指向函数的指针的教程,如果对C不是很了解的侠士,可前往一探究竟。

自己写的C#代码:

 1    class UpStatic
 2     {
 3         public delegate int calculate(int a, int b);
 4         public int add(int a, int b)
 5         {
 6             return a + b;
 7         }
 8         public int minus(int a, int b)
 9         {
10             return a - b;
11         }
12         public int multiply(int a, int b)
13         {
14             return a * b;
15         }
16         public int count(int a, int b, calculate c)
17         {
18             int result = c(a, b);
19             return result;
20         }
21 }
22 
23     class Program
24     {
25 
26         static void Main(string[] args)
27         {
28             var test = new UpStatic();
29             int p = test.count(44, 44, test.add);
30             int q = test.count(44, 44, test.minus);
31             int r = test.count(44, 44, test.multiply);
32             Console.WriteLine(p);
33             Console.WriteLine(q);
34             Console.WriteLine(r);
35             Console.Read();
36         }
37     }

悟:

空中楼阁总是令人心神不定,高以下为基。

要打好基础,才能站得稳健。

  

转载于:https://www.cnblogs.com/zhaojianrun/p/4150492.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值