什麼是委託:委託是一種安全地封裝方法的類型,它與 C 和 C++ 中的函數指針類似。與 C 中的函數指針不同,委託是面向對象的、類型安全的和保險的。委託的類型由委託的名稱定義
namespace 委託的使用
{
class Program
{
public delegate void Del(string txt);
static void Main(string[] args)
{
InitMehode();
System.Console.ReadKey();
}
public static void DelegateMethod(string txt) {
System.Console.WriteLine(txt);
}
public static void InitMehode() {
//聲明委託對象,將DelegateMethod方法作爲屬性傳遞
//說明:實例化委託是一個對象,所以可以將其作爲參數進行傳遞,也可以將其賦值給屬性。
Del hander = DelegateMethod;
hander("你好,佩奇");
//調用委託方法中帶有委託類型作爲參數hander,也可以是當前方法體DelegateMethod
MehodeCallback("張三", "北京", hander);
//上面方法對象然後調用方式
MethodClass mc = new MethodClass();
Del del1 = mc.Method1;
Del del2 = mc.Method2;
//注意,此時Method3方法列表爲:Method3(int age, string name)與上面定義委託對象參數不相符,如果想從新使用,需要定義新的委託對象列表。
//Del del3 = mc.Method3;
//按照順序依次調用MethodClass的方法,如果委託使用引用參數,則引用將依次傳遞給三個方法中的每個方法。
Del allMehode = del1 + del2;
//如果任一方法引發了異常,而在該方法內未捕獲該異常,則該異常將傳遞給委託的調用方,並且不再對調用列表中後面的方法進行調用。如果委託具有返回值和/或輸出參數,它將返回最後調用的方法的返回值和參數。若要從調用列表中移除方法,請使用減法運算符或減法賦值運算符(“-”或“-=”)【增加或刪除】
allMehode("調用了對象所有方法委託");
}
//此時將委託對象作爲參數傳遞,在調用的時候處理。
public static void MehodeCallback(string txt1,string txt2,Del callback) {
callback(txt1+txt2);
}
}
}
調用結果:
參考文章:http://shouce.jb51.net/net/index.html