命名方法(C# 編程指南)

來源:互聯網
上載者:User

 

C# 編程指南 命名方法(C# 編程指南) 委託可以與命名方法關聯。使用命名的方法對委託進行執行個體化時,該方法將作為參數傳遞,例如:C#複製代碼// Declare a delegate:delegate void Del(int x); // Define a named method:void DoWork(int k) { /* ... */ } // Instantiate the delegate using the method as a parameter:Del d = obj.DoWork;這被稱為使用命名的方法。使用命名方法構造的委託可以封裝靜態方法或執行個體方法。在以前的 C# 版本中,使用命名的方法是對委託進行執行個體化的唯一方式。但是,在建立新方法的系統開銷不必要時,C# 2.0 允許您對委託進行執行個體化,並立即指定委託將在被調用時處理的代碼塊。這些被稱為匿名方法(C# 編程指南)。 備忘作為委託參數傳遞的方法必須與委託聲明具有相同的簽名。委託執行個體可以封裝靜態或執行個體方法。儘管委託可以使用 out 參數,但不推薦將其用於多路廣播事件委託中,因為無法確定要調用哪個委託。 樣本 1以下是聲明及使用委託的一個簡單樣本。注意,委託 Del 和關聯的方法 MultiplyNumbers 具有相同的簽名 C#複製代碼// Declare a delegatedelegate void Del(int i, double j); class MathClass{    staticvoid Main()    {        MathClass m = new MathClass();         // Delegate instantiation using "MultiplyNumbers"        Del d = m.MultiplyNumbers;         // Invoke the delegate object.        System.Console.WriteLine("Invoking the delegate using 'MultiplyNumbers':");        for (int i = 1; i <= 5; i++)        {            d(i, 2);        }    }     // Declare the associated method.    void MultiplyNumbers(int m, double n)    {        System.Console.Write(m * n + " ");    }} 輸出Invoking the delegate using 'MultiplyNumbers': 2 4 6 8 10 樣本 2在下面的樣本中,一個委託被同時映射到靜態方法和執行個體方法,並分別返回特定的資訊。C#複製代碼// Declare a delegatedelegate void Del(); class SampleClass{    publicvoid InstanceMethod()    {        System.Console.WriteLine("A message from the instance method.");    }     staticpublicvoid StaticMethod()    {        System.Console.WriteLine("A message from the static method.");    }} class TestSampleClass{    staticvoid Main()    {        SampleClass sc = new SampleClass();         // Map the delegate to the instance method:        Del d = sc.InstanceMethod;        d();         // Map to the static method:        d = SampleClass.StaticMethod;        d();    }} 輸出A message from the instance method. A message from the static method.   (來源:msdn ) 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.