#include <stdio.h>
void square(int x) { printf("square of %d is %dn",x,x*x); }
void cube(int x) { printf("cube of %d is %dn",x,x*x*x); }
int main()
{
void (*calcu)(int x);
calcu=square;
calcu();
return ;
}
二.C#中委托的实质
委托又名委托类型,为什么C#弄出这个东西?因为C#是一门比较安全的语言,不允许操作指针,于是我们不能定义函数指针。但想要达到相同的效果,于是定义了委托类型。所谓委托类型,其本质就是C中的指针类型。于是代码变成了这样:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Delegate
{
class Program
{
static void square(int x) { Console.WriteLine("square of {} is {}", x, x * x); }
static void cube(int x) { Console.WriteLine("cube of {} is {}", x, x * x * x); }
delegate void math(int x); //定义委托类型
static void Main(string[] args)
{
math calcu;
calcu += square;
calcu();
Console.ReadKey();
}
}
}
可以看出,定义委托类型math实际上就相当于定义了void*类型。而委托类型实例化得到的calcu实际上就是函数指针。(说句题外话:定义函数(方法)时要加上static是因为调用函数时并未实例化,只有静态方法能够直接通过类调用)。
三.委托的使用方法
我们在上述代码19行后面加上一行代码 calcu+=cube; 运行会发现,square和cube均被调用。可以看出,符号 += 表示绑定方法到委托变量,同理符号 -= 表示取消绑定。可以理解为calcu是void **类型,即它指向了一个数组,数组中的每一项都是函数指针类型,每次调用calcu时,遍历此数组,即依次调用每个绑定的方法。
四.封装与事件的引入
下面我们要用面向对象的思想将上述代码进行封装,使其变清晰。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Delegate
{
public delegate void math(int x);
public class Calcu
{
public math calcu;
}
class Program
{
static void square(int x) { Console.WriteLine("square of {} is {}", x, x * x); }
static void cube(int x) { Console.WriteLine("cube of {} is {}", x, x * x * x); }
static void Main(string[] args)
{
Calcu c = new Calcu();
c.calcu += square;
c.calcu += cube;
c.calcu();
Console.ReadKey();
}
}
}
由于委托变量是public的,封装的程度很低,在外部可以任意修改。为了改进这个问题,C#引入了事件。










