个人理解
就是说我现在有一个方法需要实现 但是我还没有想好 可是我知道我需要输入的参数和输出的类型
那么我就可以使用委托的方式先写在这里后面在补上
三种方式
1、delegate
2、Action
3、Func
First:
delegate 需要提前声明
delegate void Something(int a);
我知道一个函数输入一个int类型的参数无返回类型
我可以在主函数之前delegate定义好后 在主函数中使用
Something a = new Something(getnum);
getnum这个参数必须要是一个static类型无返回且参数为int类型的函数名
而且不需要立马声明只需要后续声明好了就可以或者使用其他类型同条件的函数代替
Second:
Action是不需要提前定义的 节省了提前定义的步骤 简洁主要用这个
但是只能用于委托无返回参数的函数
可直接在主函数中写
Action<T,T> 函数名 = new Action<T,T>(委托的函数);
函数类型有几个写几个
third:
Func<T,T,T,out TResult>
使用方式一样只不过最后一个参数是返回值:
简单使用看下面代码
delegate void Something(int a);
static void Main(string[] args)
{
Something a = new Something(getnum);
Action Nothing = new Action(nothing);
Action<int> AddSelf = new Action<int>(addself);
Action<int,int> AddNum = new Action<int,int>(addnum);
Func<int, int, int> returnaddnumber = new Func<int, int, int>(return_addnum);
a ();
Nothing();
AddSelf(5);
AddNum(5, 6);
int k = returnaddnumber(4, 9);
}
static void getnum(int a)
{
a += 1;
}
public static void nothing()
{
}
public static void addself(int a)
{
a = a + a;
}
public static void addnum(int a, int b)
{
a = a + b;
}
public static int return_addnum(int a, int b)
{
return a + b;
}
}
还有一种就是把它当作函数指针来用
static void Main(string[] args)
{
Action<int, int> addd = new Action<int, int>(add);
Action<int, int> addd = new Action<int, int>(add);
Calculate(add, 25, 10);
Calculate(addd, 25, 10);
}
static void add(int a, int b)
{
int c= a + b;
}
static void addd(int a, int b)
{
int c= a - b;
}
static void Calculate(Action<int, int> addd, int a, int b)
{
}