委托在本质上仍然是一个类,我们用delegate关键字声明的所有委托都继承自System.MulticastDelegate。后者又是继承自System.Delegate类,System.Delegate类则继承自System.Object。委托是一种类型安全的函数回调机制, 它不仅能够调用实例方法,也能调用静态方法,并且具备按顺序执行多个方法的能力。
1. 委托也好,事件也好最初的起源是C/C++中的函数指针,什么情况下我们需要函数指针。函数指针最常用的方式就是回调(callback)——在函数内回调主函数里的函数。
#include <iostream.h>
#include <list>
using namespace std;
void max(int a, int b)
{
cout<<"now call max("<<a<<","<<b<<")..."<<endl;
int t = a>b?a:b;
cout<<t<<endl;
}
void min(int a, int b)
{
cout<<"now call min("<<a<<","<<b<<")..."<<endl;
int t = a<b?a:b;
cout<<t<<endl;
}
typedef void (*myFun)(int a, int b); //定义一个函数指针用来引用max,min
//回调函数
void callback(myFun fun, int a, int b)
{
fun(a,b);
}
void main()
{
int i = 10;
int j = 55;
callback(max,i,j);
callback(min,i,j);
}
Output:
now call max(10,55)...
55
now call min(10,55)...
10
Press any key to continue
通过转入函数指针,可以很方便的回调(callback)另外一些函数,而且可以实现参观化具体需要回调用的函数。
2 .net里一向是"忌讳"提及"指针"的,"指针"很多程度上意味着不安全。C#.net里便提出了一个新的术语:委托(delegate)来实现类似函数指针的功能。我们来看看在C#中怎么样实现上面的例子。
using System;
namespace Class1
{
class ExcelProgram
{
static void max(int a, int b)
{
Console.WriteLine("now call max({0},{1})",a,b);
int t = a>b?a:b;
Console.WriteLine(t);
}
static void min(int a, int b)
{
Console.WriteLine("now call min({0},{1})",a,b);