具有相同属性的函数或者方法(也叫具有相同的函数签名,返回类型,参数类型以及个数)抽象后就是
委托(delegate)。
觉得MSDN中的介绍很清楚,就原话搬过来了:
委托是一种引用方法的类型。一担委托分配了方法,委托将于方法具有完全相同的行为。委托和方法一样,具有参数和返回值。
如:申明一个返回俩个int类型参数的计算结果的委托
- public delegate int Computer(int x,int y);
与委托的签名(委托的签名由:返回值和参数组成)匹配的任何方法都可以分配给委托,这样就可以通过编程的方式来更改方法调用,还可以像现有类中插入新代码,只要知道委托的签名,便可以分配自己的委托方法。
将方法作为参数进行引用的能力使委托称为定义回调方法的理想选择。
委托的概述:
特点:委托类似于C++函数指针,但他是类型安全的(这个还在理解中)
委托允许将函数作为参数进行传递
委托可用于定于回调方法
委托可以连接在一起。例如:可以对一个事件调用多个方法
方法不需要与委托签名精确匹配
此类允许将代码块作为参数传递,以代替单独定义的方法
使用委托过程:1,声明一个委托,2,定义一个委托并给委托绑定调用方法,3,调用委托
使用委托例子:
- using System;
- using System.Collections.Generic;
- using System.Text;
- namespace ConsoleApplication1
- {
- //申明一个有一个string类型参数并无返回值的委托
- public delegate void Del(string message);
- class delegateTest
- {
- //定义一个静态的和委托具有相同签名的函数
- public static void DelegateMethod1(string message)
- {
- Console.WriteLine("delegateTest.DelegateMethod1 ------" + message);
- }
- //创建一个委托
- public Del handle1 = DelegateMethod1;
- //回调函数
- public void MethodWithCallBack(int x, int y, Del callback)
- {
- callback("delegateTest.MethodWithCallBack----The Number is " + (x + y));
- }
- }
- public class MethodClass
- {
- public void Method1(string message)
- {
- Console.WriteLine("MethodClass.Method1------" + message);
- }
- public void Method2(string message)
- {
- Console.WriteLine("MethodClass.Method2------"+message);
- }
- }
- class test
- {
- static void Main()
- {
- delegateTest d = new delegateTest();
- // 调用委托
- d.handle1("hello");
- //将上面创建的委托handle1传递给方法
- d.MethodWithCallBack(1, 2,d.handle1);
- Console.ReadKey();
- Console.WriteLine("---------------多路广播-----------------------");
- //-----------------------------------------------------------------
- MethodClass m = new MethodClass();
- Del d1 = m.Method1;
- Del d2 = m.Method2;
- Del d3 = delegateTest.DelegateMethod1;
- //它可以调用多个方法。这称为多路广播。若要向委托的方法列表(调用列表)中添加额外的方法,只需使用加法运算符或加法赋值运算符(“+”或“+=”)添加两个委托。
- Del d4 = d1 + d2;
- d4 += d3;
- Console.WriteLine("调用d1----结果:");
- d1("hello ");
- Console.WriteLine("调用d2----结果:");
- d2("world ");
- Console.WriteLine("调用d3----结果:");
- d3("早上好");
- Console.WriteLine("调用d4----结果:");
- d4("大家");
- Console.WriteLine("------------------委托取消方法-----------------");
- Console.ReadKey();
- Console.WriteLine("调用d4取消一个一个方法d1----结果:");
- d4 -= d1;
- d4("大家");
- Console.WriteLine("调用d4再取消一个一个方法d2(此时d4 中只调用方法)----结果:");
- d4 = d4 - d2;
- d4("大家");
- Console.ReadKey();
- }
- }
- }
下来说下匿名方法:
C#2.0中引入了匿名方法,通过匿名方法我们可以这么使用委托
public delegate int DelegateTest(int x,int y);
可以这么实例化一个匿名方法
DelegateTest del=delegate(int x,int y){return x+y;};
如果使用匿名方法,则不必创建单独的方法,减少了代码编写量。
使用委托的情况:
当用事件设计模式时
当封装静态方法可取时
当调用方不需要访问实现该方法的对象中的其他属性,方法或借口时
需要方便的组合
当类需要给方法的多个实现时
基本上都是MSDN 上的一些概念~
源自 http://msdn.microsoft.com/zh-cn/library/ms173171(VS.80).aspx