[.NET學習筆記]C#新特性——委託

來源:互聯網
上載者:User

1. delegate的定義:

定義:委託是一種引用方法的類型.一旦為委託分配了方法,委託將與該方法具有完全相同的行為.委託方法的使用可以像其他任何方法一樣,具有參數和傳回值.

其聲明如下:

public delegate string TestDelegate(string message);

在定義委託時,必須給出它所代表的方法簽名和傳回型別。 通過delegate關鍵字來聲明委託;

上面的代碼定義了一個名字叫 TestDelegate的委託,它所代表的方法有一個string參數,並且其傳回型別是string。 委託是一種特殊的物件類型,別的對象都包含資料,委託包含的是方法的地址。 可以在定義類的任何地方定義委託。

2. delegate簡單樣本

//copy by msdn,changed by Caiusing System;// Declare delegate -- defines required signature:delegate void SampleDelegate(string message);public class Delegate_Cai{    // Regular method that matches signature:    public void ShowMsg(string message)    {        Console.WriteLine(message);    }}public class Test_Delegate_Cai    {    public void Test1()    {        Delegate_Cai dd=new Delegate_Cai();        // Instantiate delegate with named method:        SampleDelegate d1=dd.ShowMsg;        // Instantiate delegate with anonymous method:        //匿名方法        SampleDelegate d2 = delegate(string message)        {            Console.WriteLine(message);        };        // Create an instance of the delegate with method;        SampleDelegate d3=new SampleDelegate(dd.ShowMsg);        d1("Hello");        d2(" World");        d3("static");    }  }

3. 應用委託、匿名方法的例子:

//-------------------------- 委託和匿名方法、lambda運算式的例子----------------------------------------    public class testDelegate2    {        //定義委託        public delegate bool stringFilter(string i);        //定義命名方法        public bool ContainFunc(string s)        {            if (s.Contains("bei") && s.Length > 5)                return true;            else                return false;        }        public List<string> SelectString(List<string> s, stringFilter startFilter)        {            List<string> str = new List<string> { };            foreach (string item in s)            {                if (startFilter(item))                    str.Add(item);            }            return str;        }        //通過委託可以編寫高可重用的代碼        public void testFunc()        {            //stringFilter myfilter = ContainFunc;            List<string> str = new List<string> { "guangdong", "hebei", "guangxi", "hunan","hubei","beijing" };            List<string> result = SelectString(str, ContainFunc);            foreach (string s in result)            {                Console.WriteLine(" " + s);            }        }        //通過匿名方法來指定委託方法        public void testFunc2()        {            List<string> str = new List<string> { "guangdong", "hebei", "guangxi", "hunan", "hubei", "beijing" };             List<string> result = SelectString(str, delegate(string s) { return (s.Contains("bei") && s.Length > 5); });            foreach (string s in result)            {                Console.WriteLine(" " + s);            }        }        //通過lambda運算式來指定委託方法        public void testFunc3()        {            List<string> str = new List<string> { "guangdong", "hebei", "guangxi", "hunan", "hubei", "beijing" };            List<string> result = SelectString(str, s => (s.Contains("h") && s.Length > 5));            foreach (string s in result)            {                Console.WriteLine(" " + s);            }        }    }

4. 委託與介面

泛型概述

   委託和介面都允許類別設計工具分離型別宣告和實現。給定的介面可由任何類或結構繼承和實現;可以為任何類中的方法建立委託,前提是該方法符合委託的方法簽名。介面引用或委託可由不瞭解實現該介面或委託方法的類的對象使用。既然存在這些相似性,那麼類別設計工具何時應使用委託,何時又該使用介面呢?

在以下情況中使用委託:

  • 當使用事件設計模式時。
  • 當封裝靜態方法可取時。
  • 當調用方不需要訪問實現該方法的對象中的其他屬性、方法或介面時。
  • 要方便的組合。
  • 當類可能需要該方法的多個實現時。

在以下情況中使用介面:

  • 當存在一組可能被調用的相關方法時。
  • 當類只需要方法的單個實現時。
  • 當使用介面的類想要將該介面強制轉換為其他介面或類類型時。
  • 當正在實現的方法連結到類的類型或標識時:例如比較方法。

聯繫我們

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