c# 委托 和 c/c++指向函数的指针 的区别

c/c++ 指向函数的指针

普通函数
int fun(int a, int b)
{
  return a > b ? a : b;
}

指向函数的指针
int (*pf)(int , int);

初始化
int (*pf)(int , int) = fun;
int (*pf)(int , int) = &fun;
赋值
pf = fun;

调用
<1> fun(1, 3);
<2> pf(1, 4); 或者 (*pf)(2,3);
-------------------------------------------------
c# 委托

普通函数
int fun(int a, int b)
{
  return a > b ? a : b;
}

定义委托
delegate int Com(int a, int b);

创建实例

Com temp = new Com(fun);

使用委托
void processDelegate(Com action, int a, int b)
{
  int result = action(a, b);
  Console.WriteLine("result is {0}", result);
}

多路委托
加普通函数
int fun2(int x, int y)
{
  return x * y;
}

Com temp2 = new Com(fun);
temp2 += new Com(fun2);
============================================================
由此可以看出委托与c/c++中指向函数的指针的区别,
定义c#中的委托像是定义一个类,然后实例化,然后使用。
而指向函数的指针则是一个单纯的函数,使用不需要在创建实例。
还有一个区别就是多路委托,这也是与指向函数的指针一个很大的区别。

总之,从这些方面看来,委托和指向函数的指针是完全不同的东西。
相同的地方可能就是c#为了解决c++中类似指向函数的指针的问题的一种手段,一种变体吧。更多的应用是用于事件

原文地址:https://www.cnblogs.com/chuncn/p/1397617.html