当前位置: 首页 > 编程语言 > C#

C#中的MulticastDelegate和GenericDelegate分享

时间:2023-04-10 12:36:42 C#

MulticastDelegate介绍每个delegate都是继承自MulticastDelegate,即每一个都是一个multicastdelegate。具有返回值的多播委托只返回最后一个方法的值。多播委托可以使用加号和减号来增加或减少操作方法。将相同的方法传递给委托时生成的委托实例也是相同的(即同一个委托)代码实现//declaredelegatedelegatevoidMulticastTest();公共类MulticastDelegateTest{publicvoidShow(){MulticastTestmulticastTest=newMulticastTest(MethodTest);多播测试();动作动作=新动作(方法测试);action=(Action)MulticastDelegate.Combine(action,newAction(MethodTest2));action=(Action)MulticastDelegate.Combine(action,newAction(MethodTest3));action=(Action)MulticastDelegate.Remove(action,newAction(MethodTest3));行动();//同上action=MethodTest;动作+=MethodTest2;动作+=MethodTest3;动作-=MethodTest3;foreach(action.GetInvocationList()中的动作action1){action1();}Console.WriteLine("==========");行动();Funcfunc=()=>{返回“我是Lambda”;};func+=()=>{返回“我是func1”;};func+=()=>{返回“我是func2”;};函数+=获取测试;函数+=获取测试;//当传递相同的方法给delegate时,生成的delegate实例也是相同的(即同一个delegate)stringresult=func();控制台.WriteLine(结果);Console.WriteLine("==========");}#region委托方法publicvoidMethodTest(){Console.WriteLine("我是方法MethodTest()1");}publicvoidMethodTest2(){Console.WriteLine("我是方法MethodTest()2");}publicvoidMethodTest3(){Console.WriteLine("我是方法MethodTest()3");}publicstringGetTest(){return"我是方法GetTest()";}#endregion通用委托代码实现//通用委托声明delegatevoidGenericDelegate(Tt);公共类GenericDelegate{publicstaticvoidInvokeDelegate(){GenericDelegategenericDelegate=newGenericDelegate(Method1);genericDelegate("我是通用委托1");//官方版(无返回值)Actionaction=newAction(Method1);action("我是一个通用委托1");//Action<字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串>GenericDelegategenericDelegate1=newGenericDelegate(Method2);genericDelegate1(2);//官方版(返回值)Funcfunc=newFunc(Method3);stringret=func("我是一个有返回值的Func委托");控制台.WriteLine(ret);//Func<字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串,字符串>;}#region委托方法publicstaticvoidMethod1(stringstr){Console.WriteLine(str);}publicstaticvoidMethod2(intnum){Console.WriteLine("我是通用委托2"+num);}publicstaticstringMethod3(stringstr){returnstr;}#endregion}以上就是C#学习教程分享的全部内容:C#中的多播委托和泛型委托,如果对大家有用,需要进一步了解C#学习教程,希望大家多多关注——本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如有转载请注明出处: