委托是一个方法指针
1.声明一个委托类型
public delegate T DelegateMethod(Paras);
2.一个要使用的方法
public T Method(Paras) {messageBox.show();}
3.实例一个委托变量
DelegateMethod s=Method;
//或
DelegateMethod s=new DelegateMethod(Method);
4.执行
s(paras);
注意事项:委托方法的声明返回值类型和参数均要与所指方法类型和参数一致。
类似c:
int *p;
int a=8;
*p=&a;
组合委托:
一个委托绑定多个方法,可以取消绑定或增加绑定。
s= MethodA+MethodB;
s+=MethodA;
s-=MethodA;
匿名方法:
DelegateMethod s=delegate(paras){messageBox.Show();};
Lambda表达式:
=>lambda运算符,读作goes to
DelegateMethod s=(paras)=>{messageBox.Show();};//无返回值的方法
进一步简化了匿名方法委托
DelegateMethod s=(int paras)=>paras++; //如果方法只有一个返回值,则可简化大括号和return;
DelegateMethod s=(paras)=>paras++; //如果方法只有一个返回值,则可简化大括号和return;参数类型列表可以写也可以不写;