帶有命名方法的委託與帶有匿名方法的委託

來源:互聯網
上載者:User

 

     在 2.0 之前的 C# 版本中,聲明委託的唯一方法是使用命名方法。C# 2.0 引入了匿名方法,而在 C# 3.0 及更高版本中,Lambda 運算式取代了匿名方法,作為編寫內聯代碼的首選方式。不過,本主題中有關匿名方法的資訊同樣也適用於 Lambda 運算式。有一種情況下,匿名方法提供了 Lambda 運算式中所沒有的功能。匿名方法使您能夠省略參數列表,這意味著可以將匿名方法轉換為帶有各種簽名的委託。這對於 Lambda 運算式來說是不可能的。匿名方法由關鍵字delegate、可選的參數列表和包含在 { 和 } 分隔字元中的語句列表組成。如果匿名方法沒有使用委託提供的參數,因此可以省略參數列表。若要獲得對參數的訪問,該匿名方法需要參數列表。 

namespace Test
{
    public partial class lambda : System.Web.UI.Page
    {
        delegate int Del(int x, int y);

        protected void Page_Load(object sender, EventArgs e)
        {
            
            //Instantiate the delegate type with an anonymous method. The result: 5
            Del d = delegate(int m, int n) { return m + n; };
            Response.Write(d(3, 2));

            //Instantiate the deledate type with a named method "add". The result: 9
            //Also can write like this: d = add;
            d = new Del(add);
            Response.Write(d(4, 5));//result: 9

            //No parameter delegate
            this.Button1.Click += delegate { Response.Write("No parameter delegate!"); };
        }

        private int add(int m,int n)
        {
            return m + n;
        }
    }
}

 

聯繫我們

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