委托是一種動態(tài)調(diào)用函數(shù)的方式,通過委托可以將一些相同類型的函數(shù)串聯(lián)起來依次執(zhí)行。委托是函數(shù)回調(diào)和事件機(jī)制的基礎(chǔ)。
委托,通過delegate關(guān)鍵字來聲明,通過new,+=,-=運算符為其分配函數(shù)。
delegate void StrParaFunc(int no,string str);//定義一個委托,沒有返回值,依次包含兩個數(shù)據(jù)類型為int和string的參數(shù)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace useDelegate
{
class Program
{
/// <summary>
/// 定義委托
/// </summary>
/// <param name="no"></param>
/// <param name="str"></param>
delegate void StrParaFunc(int no, string str);
static void PrintString(int no, string str) {
System.Console.WriteLine("{0}:PrintString:{1}",no,str);
}
static void ShowString(int no, string str)
{
System.Console.WriteLine("{0}:ShowString:{1}", no, str);
}
static void Main(string[] args)
{
//通過new初始化委托
System.Console.WriteLine("**********************");
StrParaFunc spfHandler1 = new StrParaFunc(PrintString);
System.Console.WriteLine("第一個委托對象,有1個引用函數(shù):");
spfHandler1(1,"a string 1");//委托類型中有一個引用函數(shù),結(jié)果有1個
System.Console.WriteLine("**********************");
spfHandler1 += ShowString;//通過+=增加引用函數(shù)
System.Console.WriteLine("第一個委托對象,增加了一個引用函數(shù),共2個引用函數(shù):");
spfHandler1(2,"a string 2");//委托中有兩個引用函數(shù),結(jié)果有2個
System.Console.WriteLine("**********************");
spfHandler1 -= PrintString; //通過-=移除引用函數(shù)
System.Console.WriteLine("第一個委托對象,減少了一個引用函數(shù),剩1個引用函數(shù):");
spfHandler1(3, "a string 3"); //委托中有一個引用函數(shù),結(jié)果1個
System.Console.WriteLine("**********************");
//通過函數(shù)地址直接初始化委托
StrParaFunc spfHandler2 = PrintString;
spfHandler2(4, "a string 4");
System.Console.WriteLine("**********************");
System.Console.ReadLine();
}
}
}
運行結(jié)果:
**********************
第一個委托對象,有1個引用函數(shù):
1:PrintString:a string 1
**********************
第一個委托對象,增加了一個引用函數(shù),共2個引用函數(shù):
2:PrintString:a string 2
2:ShowString:a string 2
**********************
第一個委托對象,減少了一個引用函數(shù),剩1個引用函數(shù):
3:ShowString:a string 3
**********************
4:PrintString:a string 4
**********************
posted on 2009-10-26 15:59
期待明天 閱讀(266)
評論(0) 編輯 收藏 所屬分類:
CSharp