C# 委託

來源:互聯網
上載者:User

標籤:表達   lamda   eric   參數傳遞   images   ogr   []   直接   將不   

1. 為什麼使用委託

由於三個方法中,只有一句代碼不同。可以考慮將三個方法簡化為一個,並將不同的部分作為參數傳入上述方法中。將一個方法作為參數傳遞給另一個方法,傳遞方法的類型,定義位委託類型。

2. 委託概念

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace 委託概念{    class Program    {        //將一個方法作為另一個方法的參數時,前面的方法可使用委託        //委託的定義應與其所對應的函數的標籤一致        //函數標籤,指函數的傳回值和參數        public delegate void Dele(string name);        static void Main(string[] args)        {            //1.1 初始化委託,並直接調用            //Dele dele = new Dele(SayHiChinese);            //dele("喵");            //1.2 初始化委託            //Dele dele = SayHiChinese;            //dele("喵");            //1.3 使用匿名函數初始化委託            //Dele dele = delegate(string name)            //{            //    Console.WriteLine("匿名 " + name);            //};            //dele("喵");                        //2. 委託作為另一個方法的參數            //Test("cat", SayHiChinese);            //3. 用匿名函數初始化委託            //可避免聲明多個函數,用於當函數只使用一次時            //Test("dog", delegate(string  name)            //{            //    Console.WriteLine("Anonymouse " + name);            //    Console.ReadKey();            //});            //4. lamda運算式( => goes to)和委託            Dele dele = (string name) => { Console.WriteLine("lamda運算式" + name); };            dele("cat");        }               public static void Test(string name, Dele dele)        {            dele(name);        }        public static void SayHiChinese(string name)        {            Console.WriteLine("你好嗎? " + name);            Console.ReadKey();        }        public static void SayHiEnglish(string name)        {            Console.WriteLine("How are you?" + name);            Console.ReadKey();        }    }}

 

C# 委託

聯繫我們

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