C 2 0 匿名委託

2021-03-31 08:56:31 字數 1635 閱讀 3648

delegate經常被人用來與**相比較,其實兩者在某種程度上由很多共同點。不過delegate有很多更加強大的地方。

首先,delegate中可以註冊任意多個**,在乙個delegate被呼叫的時候,已經註冊的過程將會被逐個呼叫。

其次,delegate允許註冊乙個物件的方法,而不像c++中指可以使用靜態方法或者全域性方法作為函式指標,提供了更多的靈活性,同時也暗示我們,delegate中按照某種方式儲存了object的很多資訊。

在c#2.0的匿名delegate中,我們甚至可以訪問當前匿名委託的上下文變數。接下來的文章中我們將會通過實際的例子,來看看強大的delegate。

首先,讓我們看看在c#1.2中的乙個典型的委託的寫法。

public delegate void theevent(int a);

public void test()

public void del1(int x)

", x);

}現在我們可以寫成這樣:

public void test()

或者將程式改寫為:

delegate void theevent2(int a);

public void test2()

", x); };

ev2( ref a);

}比起1.2來,delegate的可讀性更好,但是似乎沒有本質的提高?慢著,讓我們看看下面的例子。

public static void test3()

", x + y); };

ev2( ref a);

}注意,匿名函式中的內容!x + y的值被正確的輸出了,而在1.2中,委託對於區域性變數是沒有除引數外的訪問方式的。這樣做有些什麼好處呢?

讓我們看乙個更加複雜的例子:

public static void test4()

", x + y); thread.sleep(100); };

//ev2(ref a);

iasyncresult ar = ev2.begininvoke(ref a,

delegate(iasyncresult ar2)

on thread id:, is pool: ",ar2.is***pleted,thread.currentthread.gethashcode(), thread.currentthread.isthreadpoolthread);}

, null);

console.writeline("do some other calculations while counter thread is working");

console.write("work status : main thread id:, is pool: ",

ar.is***pleted,

thread.currentthread.gethashcode(),

thread.currentthread.isthreadpoolthread);

thread.sleep(500);

ev2.endinvoke(ref a, ar);

}這個例子中使用了系統執行緒池對於任務進行排隊,適合於io或者計算密集型的操作的時候。使用匿名委託最大的好處在於可以完整地轉殖當前執行空間上下文的可用變數,雖然這可能從另乙個層面上也增加了同步的複雜度,所謂有得必有失。

C 委託 匿名委託

c 委託 匿名委託 委託變數在繫結方法時,是把方法名賦值給了委託變數名,這 樣就需要在類裡面定義方法,而有些方法只用到了 次,這樣的 方法在類裡面過多時,程式的可讀性就不是太好,針對這種情 況,可以使用匿名委託,即不用在類裡面額外定義方法.delegate定義的匿名委託 格式 delegate 引數...

整理 C 2 0特性之匿名方法和迭代器

匿名方法的由來 我們在這裡用事件的定義來舉例,沒有匿名方法的時候 public partial class default system.web.ui.page protected void addclick object sender,eventargs e 有了匿名方法以後 public par...

C 2 0 新增功能

泛型 該語言中新增了一些泛型型別,使得程式設計師能夠實現程度很高的 重用,獲得更高的集合類效能。泛型型別只存在 arity 上的不同。也可以將引數強制為特定的型別。有關更多資訊,請參見泛型型別引數。迭代器 迭代器使得規定 foreach 迴圈將如何迴圈訪問集合的內容變得更加容易。分部類 分部型別定義...