[C#]透過委派執行方法

[C#]透過委派執行方法

在使用委派物件之前,必須先使用delegate關鍵字,在c#中宣告委派物件種類名稱,以及該種委派物件所可以參考的方法的回傳值型別與參數列規格
當建立好委派的規格,就可以使用new指令,根據委派的規格建立委派物件實體,以下程式,建立一個名為myHelloDelegatee的helloDelegate 委派物件,並參考到SayHello方法
當程式執行到myHelloDelegate.Invoke("Microsoft");
就會呼叫SayHello方傳並傳入參數,然後回傳Hello,Microsoft。

 

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.使用委派物件
            string message = myHelloDelegate.Invoke("Microsoft");
            Console.WriteLine(message);
            Console.ReadKey();
        }
        public static string SayHello(string pName)
        {
            string message = "Hello,";
            message += pName;
            return message;
        }
    }
}

如有錯誤 歡迎指正