c#,無處不在的委託

c#委託

委託的定義

委託是一個類,它定義了方法的型別,使得可以將方法當作另一個方法的引數來進行傳遞,這種將方法動態地賦給引數的做法,可以避免在程式中大量使用If-Else(Switch)語句,同時使得程式具有更好的可擴充套件性。

什麼是委託

首先要知道什麼是委託,用最通俗易懂的話來講,你就可以把委託看成是用來執行方法(函式)的一個東西。

如何使用委託

在使用委託的時候,你可以像對待一個類一樣對待它。即先宣告,再例項化。只是有點不同,類在例項化之後叫物件或例項,但委託在例項化後仍叫委託。

委託的宣告

委託宣告決定了可由該委託引用的方法。委託可指向一個與其具有相同標籤的方法。使用delegate 關鍵字修飾。

例如:

public delegate void Test();

上面的委託可被用於引用任何一個無引數的方法,並 且沒有返回值。

宣告委託的語法

delegate

委託的例項化

一旦聲明瞭委託型別,委託物件必須使用

new

關鍵字來建立,且與一個特定的方法有關。當建立委託時,傳遞到

new

語句的引數就像方法呼叫一樣書寫,但是不帶有引數。例如:

public delegate void Test();

Test test=new Test(TestMethod); //完整的寫法

Test test1=TestMethod; //簡寫

委託的呼叫

test。Invoke();

test1。Invoke();

例項

c#,無處不在的委託

c#,無處不在的委託

using System;

namespace weituo

{

public delegate void Test();

class Program

{

public static void TestMethod()

{

Console。WriteLine(“進行委託的測試”);

}

public static void TestMethod2()

{

Console。WriteLine(“進行多播委託的測試”);

}

static void Main(string[] args)

{

Console。WriteLine(“*******************委託的使用*************************”);

Test test = new Test(TestMethod); //委託的例項化

Test test1 = TestMethod; //委託的簡寫與test效果一樣

test。Invoke();

test1。Invoke();

Console。WriteLine(“****************多播委託的使用*************************”);

Console。WriteLine(“++++++++++++++向委託中新增一個方法++++++++++++++++++++”);

test += TestMethod2; //向委託中新增一個方法

test += delegate () //向委託中新增一個匿名方法

{

Console。WriteLine(“向委託中新增一個匿名方法”);

};

test。Invoke();

Console。WriteLine(“————————將委託中的一個方法減去——————————”);

test -= TestMethod2; //同樣委託中的方法也可以減掉

test。Invoke();

Console。WriteLine(“******************測試委託結束***********************”);

Console。ReadKey();

}

}

}

執行效果

c#,無處不在的委託

委託的多播

委託物件可使用 “+” 運算子進行合併。一個合併委託呼叫它所合併的兩個委託。只有相同型別的委託可被合併。“-” 運算子可用於從合併的委託中移除元件委託。

使用委託的這個有用的特點,您可以建立一個委託被呼叫時要呼叫的方法的呼叫列表。這被稱為委託的

多播(multicasting)

,也叫組播。下面的程式演示了委託的多播:

例項:

using System;

namespace weituo

{

public delegate void Test();

class Program

{

public static void TestMethod()

{

Console。WriteLine(“進行委託的測試”);

}

public static void TestMethod2()

{

Console。WriteLine(“進行多播委託的測試”);

}

static void Main(string[] args)

{

Console。WriteLine(“*******************委託的使用*************************”);

Test test = new Test(TestMethod); //委託的例項化

Test test1 = TestMethod; //委託的簡寫與test效果一樣

test。Invoke();

test1。Invoke();

Console。WriteLine(“****************多播委託的使用*************************”);

Console。WriteLine(“++++++++++++++向委託中新增一個方法++++++++++++++++++++”);

test += TestMethod2; //向委託中新增一個方法

test += delegate () //向委託中新增一個匿名方法

{

Console。WriteLine(“向委託中新增一個匿名方法”);

};

test。Invoke();

Console。WriteLine(“————————將委託中的一個方法減去——————————”);

test -= TestMethod2; //同樣委託中的方法也可以減掉

test。Invoke();

Console。WriteLine(“******************測試委託結束***********************”);

Console。ReadKey();

}

}

}

執行效果

c#,無處不在的委託

總結:

使用委託使程式設計師可以將方法引用封裝在委託物件內。然後可以將該委託物件傳遞給可呼叫所引用方法的程式碼,而不必在編譯時知道將呼叫哪個方法。與C或C++中的函式指標不同,委託是面向物件,而且是型別安全的。