委托是一種存儲函數引用的類型,在事件和事件的處理時有重要的用途
通俗的說,委托是一個可以引用方法的類型,當創建一個委托,也就創建一個引用方法的變量,進而就可以調用那個方法,即委托可以調用它所指的方法。
委托的使用需要以下步驟:
定義委托
delegate double ParocessDelegate(double param1,double param2);
委托的定義非常類似於函數,但不帶函數體,且要使用delegate關鍵字。委托定義需要指明委托名稱以及一個返回類型和一個參數列表
聲明委托類型的變量
ProcessDelegate process;
定義了委托後,就可以聲明一個該委托類型的變量
初始化委托變量
process =new ProcessDelegate(Multiply);
初始化委托變量時要把一個函數(此處Multiply為一個函數的名稱)引用賦給委托變量,此函數需要具有與委托相同的返回類型和參數列表。c#使用上述略顯古怪的語法,使用new關鍵字創建一個新的委托,參數為
要引用所需的函數,這是委托賦值的一個獨特語法,函數名稱是不帶括號的
還可以用另一種略微簡單的語法
process = Muiltiply;
有了引用函數的委托變量之後,我們就可以用委托變量調用Muiltiply函數;也可以把委托變量傳遞給其他函數
process (param1,param2);
示例:
namespace Delegate
{
public delegate int Call(int num1, int num2);//第一步:定義委托類型
class SimpleMath
{
// 乘法方法
public int Multiply(int num1, int num2)
{
return num1 * num2;
}
// 除法方法
public int Divide(int num1, int num2)
{
return num1 / num2;
}
}
}
class Test
{
static void Main(string[] args)
{
Call objCall;//第二步:聲明委托變量
// Math 類的對象
SimpleMath objMath = new SimpleMath();
// 第三步:初始化委托變量,將方法與委托關聯起來
objCall = new Call(objMath.Multiply);
objCall += objMath.Divide;//向委托增加一個方法
//objCall -= objMath.Divide;//向委托減去一個方法
// 調用委托實例,先執行objMath.Multiply,然後執行objMath.Divide
int result = objCall(5, 3);
System.Console.WriteLine("結果為 {0}", result);
Console.ReadKey();
}
}
注意事項:
2. 其他形式的委托
匿名委托使用起來更簡潔一點,不用在定義一個專用的委托函數來傳遞方法,也更可以更好的理解委托
//定義委托
delegate string lookMe(string s);
protected void LinkButton1_Click(object sender, EventArgs e)
{
//匿名委托
lookMe lm = delegate(string name) { return "親愛的 " + name + ",請看著我的眼睛!"; };
//匿名委托調用
string name1 = "jarod";
Label1.Text = lm(name1);
}
Action<>,Func<>,Predicate<> 其實他們都是委托代理的簡寫形式,通過他們可以省去定義委托的步驟
示例
public static void HellowChinese(string strChinese)
{
Console.WriteLine("Good morning," + strChinese);
Console.ReadLine();
}
Action<string> action = HellowChinese;
action("Spring.");
其中Action是無返回值的泛型委托,Func是有返回值的泛型委托,Predicate<>是返回bool類型的委托,他們都有多個參數的重載版本
3. 委托的各種寫法
public delegate int DelegateProcess(int num1, int num2);
//第一種寫法
DelegateProcess process= new DelegateProcess(Multiply);
//第二種寫法
DelegateProcess process= Multiply;
//第三種寫法 匿名委托
DelegateProcess process= delegate(int a,int b)
{
return a*b;
}
//第四種寫法 Lamdba表達式
DelegateProcess process =((int a,int b)=>{return a*b;});
//第五種寫法 Action<T>和Func<T>
Action<int,int> process= ((int a,int b)=>{Console.WriteLine(a * b);});
Func<int,int,int> process= ((int a,int b)=>{return a*b;});