说明委托类型,相同的返回值和参数类型;声明完成后把值和参数类型传入;委托声明类型可以生成实例
delegate void 1(string 1)
void 1(string 1){}
用委托来添加函数:无返回值,无参数的1类型生成的实例1,往里面添加函数
delegate void 1(string 1);
static func l;
static void 1(string 1)
{
}
static void 2(string 2)
{
}
static void Main(string[] args)
{
//这里两个函数要加static(静态的)不然需要你通过具体类来引用,委托同理。
l += 1;
l += 2;
}
点燃委托鞭炮,调用实例引燃:
delegate void 1(string 1);
static func l;
static void 1(string 1)
{
Console.WriteLine("你先输出了名字,参数:"+name);
}
static void 2(string 2)
{
Console.WriteLine("你又输出了主题,参数:"+title);
}
static void Main(string[] args)
{
//这里两个函数要加static(静态的)不然需要你通过具体类来引用,委托同理。
l += 1;
l += 2;
l("一个参数");
Console.ReadKey();
}
传入类型为函数也是一样的
delegate void func(string f);
static func l;
static void 1(string 1)
{
Console.WriteLine("你先输出了名字,参数:"+1);
}
static void 2(string 2)
{
Console.WriteLine("你又输出了主题,参数:"+2);
}
static void run(func l) {
l("一个参数");
}
static void Main(string[] args)
{
l += 1;
l += 2;
run(l);
Console.ReadKey();
}
如果使用=号将清空链表,使链表中只剩最后一个等号后的函数。也可以使用-=,来清除对应的函数。这里请大家自行测试。
相同案例解释一下:
delegate int func(int j,int k);
static func l;
static int 1(int x,int y){
return x + y;
}
static int 2(int x, int y) {
return x * y;
}
static void Main(string[] args)
{
l += 1;
l += 2;
Console.WriteLine(l(4,5));
Console.ReadKey();
}
运行以上返回值是20,结果是最后一个函数返回值。如何获取每个函数的返回值,这里写了一个示例:
delegate int func(int j,int k);
static func l;
static int 1(int x,int y){
return x + y;
}
static int 2(int x, int y) {
return x * y;
}
static void Main(string[] args)
{
l += 1;
l += 2;
foreach(Delegate i in l.GetInvocationList()){
func k=(func)i;
Console.WriteLine(k(4,5));
}
Console.ReadKey();
}
- 委托是一种类型
- 委托是一种类型与返回值相同函数的链表
- 委托使用+=,=,-=三个符号操作链表里的函数
- 调用委托就会依次调用委托链表里的所有函数
- 委托返回值默认是最后一个添加的函数返回值