• 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
    ", 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     }

    悟:

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

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

      

  • 相关阅读:
    Serverless Wordpress 系列建站教程(五)
    剑指 Offer 13. 机器人的运动范围
    剑指 Offer 12. 矩阵中的路径
    网络相关知识
    网络相关知识(TCP部分)
    笔试中的流程控制题
    笔试:一些怕忘掉的基础东西
    笔试:处理输入基础
    设计模式:行为型->观察者模式
    设计模式:结构型->代理模式
  • 原文地址:https://www.cnblogs.com/zhaojianrun/p/4150492.html
Copyright © 2020-2023  润新知