->委托是一种类型,事件是委托的实例。
->自定义委托与事件实例:
委托调用方:
public delegate void **InfoFormHandler**(string name);//定义委托
public class Fun
{
//委托的事件实例
public static event **InfoFormHandler** eventInfo;
//调用函数
public void Display()
{
if (eventInfo != null) {
eventInfo.Invoke("嗨");
}
}
}
事件注册方:
public class Regist
{
public Regist()
{
Fun.eventInfo += Fun_eventInfo;//注册事件
Fun.eventInfo += Fun_eventInfo1;//注册事件
}
private void Fun_eventInfo1(string name)
{
Console.WriteLine("{0},zhuyi,lih",name);
}
private void Fun_eventInfo(string name)
{
Console.WriteLine("{0},zhuyi,",name);
}
}
//主程序:先注册然后再调用
class Program
{
static void Main(string[] args)
{
new Regist();//注册
Fun fun = new Fun();
fun.Display();//调用
Console.ReadLine();
}
}
运行结果:
嗨,zhuyi,
嗨,zhuyi,lih
->微软提供的几种内置的委托类型:Action、Func、Predicate等,主要是减少自定义委托;
Action委托:
1)Action是一种无参的,没有返回值的委托类型;
2)Action右16个泛型重载,泛型委托,T为参数:Action,Action<T1,T2>,…
Func委托:
1)必须有一个返回值;
2)Func泛型委托,Func<>中最后一个参数为返回类型
class Register
{
Func<string> funcHandle;//无参
Func<string, int> funcHandlePara;//有一个参数string类型,int为返回值类型
public Register()
{
//注册事件
funcHandle += invokeMethod;
funcHandlePara += InvokeMethodPara;
}
public string invokeMethod()
{
Console.WriteLine("无参方法");
return "无参";
}
public int InvokeMethodPara(string num)
{
Console.WriteLine("有参方法");
return 10;
}
///委托调用
public void Display()
{
funcHandle.Invoke();
funcHandlePara.Invoke("you");
}
}
Predicate委托:
1)只接受一个参数;
2)必须返回bool类型;
3)类似于Func<T,bool>类型的委托。
->委托的取值与清空
取值: handler.GetInvocationList(),返回委托列表,handler为声明的委托
清空委托的注册方法:handler -=this.handler;//清空注册的方法,handler为声明的委托