委托类型
委托時一種特殊的類型,它用來保存方法的地址,這樣我們很方便的調用方法,像變量一樣傳遞,回調。
C++中的函數指針也是保存方法的地址,但是有一點不一樣的是定義委托的時候就知道了它里面可以保存什么樣的方法,而函數指針就沒有這些
所以委托相對更明確一點,更安全一點。
?
public delegate void MyDelegate(int x) //這樣的委托類型表示,該委托可以用來保存無返回值,切參數為int類型的方法?
當然當我們寫出上面那段代碼的時候,實際上編譯器做了其他一些事,實際可能定義像下面這樣的
public class MyDelegate:system.MusticastDelegate{public MyDelegate(object obj,IntPtr method){……} //obj保存,方法的實例(靜態方法則null),IntPtr保存方法地址public virtual void Invoke(int value){……} //調用方法 ……//省略 }MusticastDelegate 內部有
_target字段 //保存當前委托保存方法,要使用的實例
_methodPtr字段 //保存委托保存的方法
_invoalcationList字段 //保存委托鏈(如果只有一個委托就Null)
public class MyClass{Public void Method1(int y){}public static void Method2(int y){}}1、當我們使用MyDelegate del = new MyDelegate(new MyClass().Method1);
那么del對象中_target則保存了new MyClass()實例
_methodPtr保存了Method1地址
_invoalcationList此時為NULL,因為只有一個委托
當我們調用del(10),實際上是調用del.Invoke(10) 然后Invoke執行的是_target._methodPtr(10)
?
2、當我們使用MyDelegate del2 = new MyDelegate(MyClass.Method2);
那么del2對象中_target則保存了NULL,因為是保存靜態方法,所以沒有對象
_methodPtr保存了Method2地址
_invoalcationList此時為NULL,因為只有一個委托
當我們調用del2(10),實際上是調用del2.Invoke(10) 然后Invoke執行的是_target._methodPtr(10) 因為_target是null,所以實際是MyClass._methodPtr
?
3、del+=del2
那么實際是執行了del = Delegate.Combine(del,del2)
內部是創建了_invoalcationList數組,里面包含有兩個委托del,del2
_target =null
_methodPtr =Method2地址
當我們調用del(10)時發現_invoalcationList里面有兩個委托,則循環這個數組,分別調用每個委托
轉載于:https://www.cnblogs.com/fuyun2000/p/3439994.html
總結
- 上一篇: 收入时间序列——之预测总结篇
- 下一篇: 最大子图形问题