事件与驱动函数的对应关系就是通过委托(Delegate)类来关联的
跨线程对控件进行操作 -----》委托(Delegate)
其实委托(Delegate)类这种数据结构有些类似于之前C/C++中的函数指针。
函数指针用指针获取一个函数的入口函数,实现对函数的操作。
委托与C/C++中函数指针的不同之处是:委托是面向对象的,类型安全的和保险的,是引用类型,因此对委托的使用要“先定义,后声明,接着实例化,然后作为参数传递给方法,最后才能使用”。
一般语法为(定义委托使用关键字delegate):
public delegate double MyFunction(type1 para1,type2 para2...);
定义了一个名为MyFunction的委托。编译器编译这行代码时,会自动为其生成一个继承自System.Delegate的类型,类型的名称为MyFunction。
声明委托:
Myfunction d;
实例化委托:
d = new Myfunction(obj.InstanceMethod);
其中obj是对象,InstanceMethod是他的实例方法。然后用用作某方法的参数:
Recvfunc(d);
最后在此方法的实现代码中使用:
private void Recvfunc(Myfunction s)
{
s(arg1,arg2,arg3,...argn);
....
}
通过委托SomeDelegate实现对方法InstanceMethod的调用,调用还必须有一个前提条件:方法InstanceMethod有参数且和定义Myfunction的参数一直,且返回类型相同
方法与委托相关联
委托是对方法的封装,相当于一个容器,它封装了我们想要实现的若干方法,当调用委托对象时候,就会顺序执行它所封装的所有方法,委托链的形成可以用“+=”或“-=”对不同的委托实例进行二次操作,此步骤为方法与委托的绑定与移除
方法与委托的绑定
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Delegate
{
public delegate void MyDelegate();
class Program
{
static void Main(string[] args)
{
Program p = new Program();
MyDelegate myDel = new MyDelegate(p.Read);
myDel += p.Play;
myDel += p.Watch;
myDel();
myDel -= p.Read;
myDel();
Console.ReadLine();
}
public void Read()
{
Console.WriteLine("Read a book");
}
public void Play()
{
Console.WriteLine("Play games");
}
public void Watch()
{
Console.WriteLine("Watch TV");
}
}
}
运行效果