资源描述:
《《委托和事》PPT课件》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、1第6章委托和事件委托的概念面向对象的核心思想之一就是将数据和对数据的操作封装为一个整体。委托变量可以看成是一种安全的函数指针,它只能接受符合其要求的函数地址。函数传递的是数据对象委托(delegate)传递的是函数本身委托和方法3委托封装方法委托类型定义delegatevoidDualFunction(intx,inty);publicstaticvoidAdd(intx,inty){Console.WriteLine("{0}+{1}={2}",x,y,x+y);}与要绑定的方法原型一致委托和方法4委托封装方法委托类型
2、定义委托对象创建delegatevoidDualFunction(intx,inty);publicstaticvoidAdd(intx,inty){Console.WriteLine("{0}+{1}={2}",x,y,x+y);}publicstaticvoidMain(){DualFunctionfun1=newDualFunction(Add);}委托和方法5委托封装方法委托类型定义委托对象创建调用方法delegatevoidDualFunction(intx,inty);publicstaticvoidAdd(i
3、ntx,inty){Console.WriteLine("{0}+{1}={2}",x,y,x+y);}publicstaticvoidMain(){DualFunctionfun1=newDualFunction(Add);Add(1,2);fun1(1,2);}与一般方法调用格式相同委托和方法6委托封装方法DualFunctionfun1=newDualFunction(Add);fun1AddvoidAdd{intx,inty)......voidSub{intx,inty)......voidMul{intx,in
4、ty)......委托和方法7委托封装方法DualFunctionfun1=newDualFunction(Add);fun1(2,3);fun1AddvoidAdd{intx,inty)......voidSub{intx,inty)......voidMul{intx,inty)......委托和方法8委托封装方法DualFunctionfun1=newDualFunction(Add);fun1(2,3);fun1=newDualFunction(Sub);fun1AddvoidAdd{intx,inty).....
5、.voidSub{intx,inty)......voidMul{intx,inty)......委托和方法9委托加减DualFunctionfun1=newDualFunction(Add);fun1(2,3);fun1+=newDualFunction(Mul);fun1AddMulvoidAdd{intx,inty)......voidSub{intx,inty)......voidMul{intx,inty)......委托和方法10委托加减DualFunctionfun1=newDualFunction(Add)
6、;fun1(2,3);fun1+=newDualFunction(Mul);fun1(2,3);fun1AddMulvoidAdd{intx,inty)......voidSub{intx,inty)......voidMul{intx,inty)......委托和方法11传递委托对象作为方法参数作为方法返回值委托和方法12Delegate类型DynamicInvokeFun1(2.5,2)Fun1.DynamicInvoke(2.5,2)Combine/RemoveDualFunctionfun3=fun1+fun2Du
7、alFunctionfun3=(DualFunction)(Delegate.Combine(fun1,fun2);匿名方法13委托调用方法命名方法匿名方法publicstaticvoidAdd(intx,inty){Console.WriteLine("{0}+{1}={2}",x,y,x+y);}......DualFunctionfun1=newDualFunction(Add);DualFunctionfun1=delegate(intx,inty){Console.WriteLine("{0}+{1}={2}",
8、x,y,x+y);}匿名方法14外部变量doublea=2.5,b=2;DualFunctionfun1=delegate(inta,intb){a++;b++;}fun1(a,b);DualFunctionfun2=delegate(inta,intb){a++;b--;}fun2(a,b);捕获外部