[C#]匿名委派

[C#]匿名委派

匿名方法本身是委派的精簡版本,以一種更為簡潔的方式,完成委派的引用。
我們不需為了傳遞實體方法而建立方法成員的類別實體,
只要經由delegate關鍵字直接將方法內容程式碼傳入即可。
修改 [C#]透過委派執行方法 這篇的範例 改成匿名委派


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        public delegate string helloDelegate(string pName);//1.宣告委派規格
        static void Main(string[] args)
        {
            //helloDelegate myHelloDelegate = new helloDelegate(SayHello);//2.使用委派物件
            helloDelegate myHelloDelegate = delegate(string pName)
            {
                string message = "Hello,";
                message += pName;
                return message;
            };
            //string message = myHelloDelegate.Invoke("Microsoft");
            string msg = myHelloDelegate("Microsoft");

            Console.WriteLine(msg);
            Console.ReadKey();
        }
        //public static string SayHello(string pName)
        //{
        //    string message = "Hello,";
        //    message += pName;
        //    return message;
        //}
    }
}

 


如有錯誤 歡迎指正