using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 委托
{
//此处介绍了Csharp中最常用的两个委托 Action 和 Func
class Program
{
//delegate 委托 C 中使用指针代替直接调用
//委托是指针的升级版本
//函数指针 直接调用与 间接调用的结果是一致的
static void Main(string[] args)
{
Caculator caculator = new Caculator();
Action action = new Action(caculator.Report); //此处只需要方法名 不要加圆括号 这里不是调用
//此时 已经使用了 Action 指向了 Report 这个方法
caculator.Report();//此处为直接调用
action.Invoke(); //此处为间接调用 与直接调用效果是一样的
action();
//使用Function 委托
Func<int, int, int> func1 = new Func<int, int, int>(caculator.Add); //委托的目标 输入两个int 返回的值为int
Func<int, int, int> func2 = new Func<int, int, int>(caculator.Sub);
int x = 100;
int y = 200;
int z = 0;
int o = 0;
z = func1.Invoke(x,y); //委托 使用了间接调用
o = func2(x, y);
Console.WriteLine("z的结果数值是:"+z);
Console.WriteLine("o的结果数值是:"+ o);
Console.Read();
}
}
class Caculator
{
public void Report()
{
Console.WriteLine("I have 3 methods");
}
public int Add(int a, int b)
{
int result = a + b;
return result;
}
public int Sub(int a, int b)
{
int result = a - b;
return result;
}
}
}
//一切皆地址
//直接调用 通过函数名直接获得函数所在的地址并且开始执行
//间接调用 函数指针 cpu 找到存储的地址开始执行
//委托是函数指针的升级版