多播委托浅析
飲水思源
http://www.cnblogs.com/huashanlin/archive/2008/03/11/1100870.html
Overview
本文主要,來學習一下,多播委托 , 這個名詞可能比較生僻一點,通過語言很難表達出來,下面我們還是通過代碼來說明吧,我本身對這些概念性的東西,就不太感冒...露怯了。
多播委托
- 一個委托對象,包含一個以上的方法被稱為多播委托。
Demo
一個簡單的委托
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace UnderstandDelegate {public delegate void SayHelloHandler(); }Person類
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace UnderstandDelegate {public class Person{public void SayHello(SayHelloHandler handler){handler.Invoke();}} }調用
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks;namespace UnderstandDelegate {class Program{static void Main(string[] args){//想不到還有這種操作吧SayHelloHandler handler = ChinaStyleSayHello;handler += EnglishStyleSayHello;handler += JapanStyleSayHello;new Person().SayHello(handler);}static void ChinaStyleSayHello(){Console.WriteLine("你好");}static void EnglishStyleSayHello(){Console.WriteLine("Hello");}static void JapanStyleSayHello(){Console.WriteLine("坑你急哇");}} }輸出結果
你好 Hello 坑你急哇好,這就是我們的多播委托 , 概念性的東西太難理解了.
多播委托淺析
還記得我們分析,委托原理的時候,說過的委托的繼承關系嗎:
自定義委托 繼承自 MulticastDelegate 繼承自 Delegate .
現在我們來看一看 MulticastDelegate 類。
其中我們需要值得注意的方法
//移除一個委托元素從這個多播委托的tion list中。 [SecuritySafeCritical] protected sealed override Delegate RemoveImpl(Delegate value); //將一個該委托和一個指定的委托聯合起來,產生一個新的委托對象。 [SecuritySafeCritical] protected sealed override Delegate CombineImpl(Delegate follow); //返回多播委托的列表,以調用的順序排序 [SecuritySafeCritical] public sealed override Delegate[] GetInvocationList();看一看反編譯
static void Main(string[] args) {//想不到還有這種操作吧SayHelloHandler handler = ChinaStyleSayHello;handler += EnglishStyleSayHello;handler += JapanStyleSayHello;new Person().SayHello(handler); } //被反編譯為了如下代碼 private static void Main(string[] args) {SayHelloHandler sayHelloHandler = new SayHelloHandler(Program.ChinaStyleSayHello);sayHelloHandler = (SayHelloHandler)Delegate.Combine(sayHelloHandler, new SayHelloHandler(Program.EnglishStyleSayHello));sayHelloHandler = (SayHelloHandler)Delegate.Combine(sayHelloHandler, new SayHelloHandler(Program.JapanStyleSayHello));new Person().SayHello(sayHelloHandler); }我們的+= 運算,最后編譯成了 調用Delegate.Combine 靜態方法的形式,我們的編譯器真是太智能了,我們來看一下Delegate.Combine 方法的源碼,又用到了我們 強大又免費的ILSpy 工具了。
public static Delegate Combine(Delegate a, Delegate b) {if (a == null){return b;}//最后還是調用了我們的 MulticastDelegate類中的CombineImpl方法return a.CombineImpl(b); }或許這里你可能有以為,這里不是調用的是Delegate類的方法嗎? 不 請注意: Delegate 類的CombineImpl 方法是一個虛方法,MulticastDelegate 類重寫了他,因為所有的委托都遵循著這樣的繼承規律:自定義委托 繼承自 MulticastDelegate 繼承自 Delegate .
在這里看著是調用的Delegate類的CombineImpl 方法,但是由于MulticastDelegate 類重寫了該方法,所以,這里本質上調用的 MulticastDelegate 類的方法。
結語
本章的內容就到這里,如果還有好奇,可以繼續通過我們的ILSpy 工具,往深處研究,這里就不在贅述。畢竟筆者水平也有限。
轉載于:https://www.cnblogs.com/slyfox/p/7512355.html
總結
- 上一篇: Gson 使用总结 高级用法
- 下一篇: C++:用成员初始化列表对数据成员初始化