码迷,mamicode.com
首页 > Windows程序 > 详细

C#的delegate与C的函数指针

时间:2014-12-08 10:42:23      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   io   ar   color   os   sp   on   

引子:

一个小示例,希望可以帮助广大侠士们来理解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     }

悟:

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

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

  

C#的delegate与C的函数指针

标签:style   blog   http   io   ar   color   os   sp   on   

原文地址:http://www.cnblogs.com/zhaojianrun/p/4150492.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!