.method public hidebysig newslot virtual
instance void Invoke (
int32 times
) runtime managed
{
} // end of method DoSomething::Invoke
.method public hidebysig newslot virtual
instance class [mscorlib]System.IAsyncResult BeginInvoke (
int32 times,
class [mscorlib]System.AsyncCallback callback,
object 'object'
) runtime managed
{
} // end of method DoSomething::BeginInvoke
.method public hidebysig newslot virtual
instance void EndInvoke (
class [mscorlib]System.IAsyncResult result
) runtime managed
{
} // end of method DoSomething::EndInvoke
} // end of class delegates.DoSomething
二. 定義了委托,當(dāng)然是為了使用它,來看下如何使用委托:
在.Net中有三種委托的形式,分別是方法、匿名方法和lambda表達(dá)式;我們用方法定義的形式看下委托的使用方法
代碼如下:
using System;
namespace delegates
{
public delegate void DoSomething(int times);
class Program
{
static void Main(string[] args)
{
//聲明委托變量并給委托變量賦值
DoSomething @do = DoA;
//可以使用+號(hào)或者+=給委托增加方法
@do += DoB;
//執(zhí)行委托時(shí)將按照委托的添加順序先后執(zhí)行委托中的方法
@do(1);
//也可以通過-號(hào)或者-= 從委托中移除方法
@do -= DoA;
@do(2);
@do -= DoB;
//將委托中的所有方法都移除掉之后,委托照樣是可以調(diào)用的,只是什么都不做
@do(3);
Console.Read();
}
//定義一個(gè)委托相同參數(shù)和返回值的方法
static void DoA(int times)
{
Console.WriteLine("Do A {0}", times);
}
//定義一個(gè)委托相同參數(shù)和返回值的方法
static void DoB(int times)
{
Console.WriteLine("Do B {0}", times);
}
}
}
如上代碼中的Main方法,首先我們定義了委托DoSomething的變量@do,并將DoA方法直接賦值給此委托變量;然后我們又使用+=符號(hào)或者+號(hào)給此委托添加了另一個(gè)方法;當(dāng)然也可以使用-或者-=從委托中去掉方法。
委托比C/C++方法指針強(qiáng)大的地方在于其可以容納多個(gè)方法,也可以執(zhí)行+/-操作從方法列表中添加或者刪除掉方法。
在執(zhí)行委托加減運(yùn)算時(shí)有幾個(gè)問題需要我們注意:
1. 委托聲明的寫法
委托聲明時(shí)可以用如下寫法
代碼如下:
DoSomething @do = DoA;
這其實(shí)是一種簡(jiǎn)短的寫法,我們知道在.Net 1.x中這樣寫是不允許的只有到.Net 2.0時(shí)才允許這么寫,在.Net 1.x中必須寫成
代碼如下:
DoSomething @do = new DoSomething(DoA);
我們要在聲明時(shí)就給@do賦予DoA加上DoB
代碼如下:
DoSomething @do = DoA + DoB;
這么寫是不行的,編譯器不干了;必須使用.Net 1.x中的寫法
代碼如下:
DoSomething @do = new DoSomething(DoA) + new DoSomething(DoB);
2. 從委托中減去委托中本不存在的方式時(shí)會(huì)發(fā)生什么呢?
請(qǐng)看如下代碼:
代碼如下:
DoSomething @do = DoA;
@do -= DoB;
第一行代碼我生命了@do并將DoA賦予它;第二行代碼我嘗試從@do中減去DoB,DoB并沒有在@do的方法列表中存在,這樣會(huì)發(fā)生什么情況呢?首先編譯器沒有報(bào)錯(cuò),程序可以正常的編譯;執(zhí)行代碼發(fā)現(xiàn)可以程序可以正常執(zhí)行,調(diào)用@do委托時(shí)正確的執(zhí)行了DoA方法;這說明了.Net包容了我們程序員犯的錯(cuò),我們從委托變量中減去一個(gè)委托中并不包含的方法時(shí),不會(huì)報(bào)錯(cuò)會(huì)正常的執(zhí)行。
3. 對(duì)委托做減法,所有委托都減完了,會(huì)怎樣呢?看如下代碼
代碼如下:
DoSomething @do = new DoSomething(DoA) + new DoSomething(DoB);
@do -= DoA;
@do -= DoB;
@do(1);
這樣的代碼可以成功編譯,但是在運(yùn)行時(shí)會(huì)報(bào)NullReferenceException;這顯然不是我們希望的,所以對(duì)委托做減法時(shí)要特別注意。
代碼如下:
<span style="text-decoration: line-through;">public delegate void DoIt(string task);
class Test
{
static void Main(string[] args)
{
//DoIt聲明,賦予一個(gè)參數(shù)更寬泛的方法是合法的
DoIt doIt = new DoIt(DoItImpl);
doIt("hello");
}
//比委托定義中的參數(shù)更寬泛,string類型可以隱式轉(zhuǎn)換成object
static void DoItImpl(object task)
{
Console.WriteLine("DoItImpl {0}",task);
}
}
</span>
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com