函数指针
c
#include<stdio.h>
//声明函数指针
typedef int(*Calc)(int a, int b);
int Add(int a, int b)
{
return a + b;
}
int Sub(int a, int b) {
return a - b;
}
int main() {
Calc funcPoint1 = &Add;
Calc funcPoint2 = ⋐
int x = 120;
int y = 140;
int z = 0;
z = Add(x, y);
z = funcPoint1(x, y);
printf("%d+%d=%d\n", x, y, z);
z = Sub(x, y);
z = funcPoint2(x, y);
printf("%d-%d=%d\n", x, y, z);
system("pause");
}
一切皆地址
变量(数据):是以某个地址为起点中的一段内存中所存储的值;
函数(算法):是以函数名为地址起点的一段内存中所存储的一组机器语言指令;
C#中委托是什么?
委托(delegate)是函数指针的'升级版';
委托的简单使用
- Action委托
- Func委托
csharp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FunctionPointerExampleCsharp
{
class Program
{
static void Main(string[] args)
{
Calculator ca = new Calculator();
Action action = new Action(ca.Report);
ca.Report();
action.Invoke();
action();
Func<int, int, int> func = new Func<int, int, int>(ca.Add);
Func<int, int, int> func2 = new Func<int, int, int>(ca.Sub);
int result=func.Invoke(12, 34);
Console.WriteLine(result);
result=func2.Invoke(123, 34);
Console.WriteLine(result);
result =func(12, 34);
Console.WriteLine(result);
result =func2(123, 34);
Console.WriteLine(result);
}
}
class Calculator
{
public void Report()
{
Console.WriteLine("Hello,Tom!");
}
public int Add(int a, int b)
{
return a + b;
}
public int Sub(int a, int b)
{
return a - b;
}
}
}