C#委托
文章目录
- C#委托
- 委托定义
- 委托实例化
- Action与Func
委托是一种动态调用方法的类型,委托是对方法的抽象和封装。
函数指针。
调用委托时,委托包含的所有方法将被执行。
委托定义
delegate关键字
修饰符 delegate 返回值类型 委托名( 参数列表 );
public delegate int myDelegate(int x ,int y);
委托实例化
命名方法委托在实例化时必须带入方法的具体名称
委托名 委托对象名 = new 委托名( 方法名 );
调用委托
委托对象名( 参数列表 );
using System;class Program {public delegate int AddDelegate(int x,int y);static void Main(string[] args){AddDelegate addDelegate = new AddDelegate((new Test()).Add2num);Console.WriteLine(addDelegate(1,2));}
}class Test{public int Add2num(int x,int y){return x+y;}
}
定义委托,形参要有名称
Action与Func
Action和Func是系统预定义的委托。
Action是无返回值的泛型委托,Action有两种形式:
- 没有返回值也不可以带参数
Action
- 没有返回值,但是可以带参数
Action<>
, 参数限制0~16个
Func是有返回值泛型委托, Func有两种形式
-
有返回值,无参数
Func<返回值类型>
必须有返回值 -
有返回值,有参数
Func<参数1,参数2,返回值类型>
必须有返回值和参数,参数0~16个
使用Func改写上面的委托代码
using System;class Program {static void Main(string[] args){Func<int,int,int> addDelegate = new Func<int,int, int>((new Test()).Add2num);Console.WriteLine(addDelegate(1,2));}
}class Test{public int Add2num(int x,int y){return x+y;}
}
Action和Func参数类型使用泛型定义,不能给形参名称