委托又给我惹麻烦了————记委托链的取消注册、获取返回值
生活随笔
收集整理的這篇文章主要介紹了
委托又给我惹麻烦了————记委托链的取消注册、获取返回值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
今天改bug碰到了一個問題,有多個方法注冊到了一個事件里去,而這些方法本身又有點兒互斥,因而造成了bug,哥調試半天才發現,郁悶至極,遂復習了以前的知識并進行適當延伸,再將成果記錄及分享之,以防他日再犯。
顯然這是一個委托鏈,那么首先就來回顧下委托鏈的最初寫法了,這里引用上一篇?委托的N種寫法,你喜歡哪種??的部分代碼。
定義委托:
delegate string PlusStringHandle(string x, string y);定義對應的方法:
static string plusString(string x, string y){Console.WriteLine("plusString方法被調用......");return x + y;}?
調用:
PlusStringHandle handle = null;handle += plusString;handle += plusString;string str = handle("aa", "bb");Console.WriteLine("調用委托獲取返回值:{0}", str); Console.WriteLine("委托注冊的默認方法名:{0}", handle.Method.Name);結果:
再定義一個方法:
static string testString(string x, string y){Console.WriteLine("testString方法被調用.......");return x + x + y + y;}使用-=:
PlusStringHandle handle = null;handle += plusString;handle += plusString;handle += testString;handle -= plusString;handle -= testString;string str = handle("aa", "bb");Console.WriteLine("調用委托獲取返回值:{0}", str); Console.WriteLine("委托注冊的默認方法名:{0}", handle.Method.Name);運行發現仍然調用了 plusString 方法,這就是產生文中開頭所說的bug的原因了。
繼續修改Main方法:
PlusStringHandle handle = null;handle += plusString;handle += plusString;handle += testString;//handle -= plusString;//handle -= testString;handle = testString; //或者先將handle置為null再使用+=string str = handle("aa", "bb");Console.WriteLine("調用委托獲取返回值:{0}", str); Console.WriteLine("委托注冊的默認方法名:{0}", handle.Method.Name);這就是我要的結果,讓委托不再受以前注冊過的方法影響。
=======================分割線 =============================
?
以下繼續來探討下委托鏈獲取的返回值,如上文所寫,直接調用委托只能獲取最后一次注冊的方法的返回值,那么假如說要獲取所有已注冊的方法的返回值則有兩種方式:
PlusStringHandle handle = null;handle += plusString;handle += plusString;handle += testString;string str = handle("aa", "bb");Console.WriteLine("調用委托獲取返回值:{0}", str); Console.WriteLine("委托注冊的默認方法名:{0}", handle.Method.Name);Delegate[] delegates = handle.GetInvocationList();Console.WriteLine("以下遍歷獲取委托鏈中的返回值==============================================");foreach (PlusStringHandle d in delegates){Console.WriteLine("調用的方法:{0},獲取方法返回值:{1}", d.Method.Name, d("qq", "ww"));}foreach (Delegate d in delegates){//d即為PlusStringHandle類型Console.WriteLine("調用的方法:{0},獲取方法返回值:{1}", d.Method.Name, d.DynamicInvoke("qq", "ww"));}說是兩種方式,其實異曲同工,不同的寫法,其中一種是動態調用而已了。
轉載于:https://www.cnblogs.com/FreeDong/p/3248283.html
總結
以上是生活随笔為你收集整理的委托又给我惹麻烦了————记委托链的取消注册、获取返回值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: QuickPart应用系列
- 下一篇: 大数据生态与Spark简介