C#/.Net中的委託(Delegates)和事件(Events) 待續。。。

來源:互聯網
上載者:User

原文地址:Delegates and Events in C# / .NET

委託(Delegates)
C#中的委託類似於C/C++的指標功能。使用委託可以讓程式員在委派物件裡傳引用給方法。委派物件被傳遞給調用引用方法的代碼,而不是在編譯的時候調用方法。

直接調用方法 - 不使用委託
在大多數的情況下,當我們需要調用方法的時候,我們直接調用指定的方法。如果有個類MyClass的方法Process,我們通常用這個方法調用(SimpleSample.cs):  

 1using System;
 2 
 3namespace Akadia.NoDelegate
 4{
 5    public class MyClass
 6    {
 7        public void Process()
 8        {
 9            Console.WriteLine("Process() begin");
10            Console.WriteLine("Process() end");
11        }
12    }
13 
14    public class Test
15    {
16        static void Main(string[] args)
17        {
18            MyClass myClass = new MyClass();
19            myClass.Process();
20        }
21    }
22} 

在多數情況下是沒有問題的。但是有時候,我們不想直接調用方法,更願意能傳到其他地方,以至於能夠調用。當使用者點擊按鈕等情況下,我想執行一些代碼的情況發生時,類似GUI等事件驅動的系統,委託就相當有用。

非常簡單的委託
委託的一個有趣而有用的屬性,它不需要知道或關心它所引用的類的對象。任何的對象將能做到,問題在於方法的參數類型和傳回值類型需要和委託的參數類型和傳回值類型匹配。這使得委託能完美的適用於“匿名”調用。
單播委託的語句格式如下:

delegate result-type identifier ([parameters]); 

where: 
result-type: The result type, which matches the return type of the function. 
identifier: The delegate name. 
parameters: The Parameters, that the function takes. 

例如:

public delegate void SimpleDelegate ()

這個申明定義了名為SimpleDelegate的委託,能夠傳任何沒有參數和傳回值的方法。

public delegate int ButtonClickHandler (object obj1, object obj2)

這個申明定義了名為ButtonClickHandler的委託,能夠傳任何含有兩個對象和傳回值為整型的方法。

待續。。。

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.