上篇 已经说到委托实际上可以理解成一类方法的类型,这样类型自然可以作为方法的参数传递。
例子:
public Delegate string TestEventHander(string Name);//定义委托
public class Student
{
public void GetDelegate(string Name,TestEventHander test)//委托做为参数传递,实现了方法做为方法的参数进行传递
{
test(Name);
}
}
static void Main(sting[] args)
{
Student stu=new Student();
stu.GetDelegate("Jone",GetName);
stu.GetDelegate("1011",GetID);
//TestEventHander aa,bb;
//aa=GetName;bb=GetID;
//aa+=GetID;//增加新的方法到委托变量中
//aa-=GetID;//移除新的方法
//stu.GetDelegate("Jone",aa);
//stu.GetDelegate("1011",bb);
public string GetName(string Name)
{
return Name;
}
public string GetID(string ID)
{
return ID;
}
}
//使用委托可以将多个方法绑定到同一个委托变量,当调用此变量时,可以依次调用变量所绑定的所有方法
那么就该说事件了。C#中事件就是委托的一种应用
事件不过就是类似于声明一个委托类型的变量,是一种观察者模式的一种实现方式