[C#]擴充方法

[C#]擴充方法

擴充方法讓新建立的方法,可以被加入至現有的型別之中,不需要另外建立新的衍生型別,或是對原來的型別進行修改,即可擴充其功能。
包含擴充方法的類別必須是宣告為static靜態類別,而其中的方法成員必須是public 與 static型態,方法第一個參數必須以this關鍵鍵字作宣告
以下為擴充方法的範例


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

namespace UExtensionMethod
{
    class Program
    {
        static void Main(string[] args)
        {
            string strName = "God";
            string message = strName.SayHello();
            Console.WriteLine(message);
            Console.ReadKey();
        }
    }
    public static class ExtensionString
    {
        public static string SayHello(this string str)
        {
            string helloMessage;
            helloMessage = "Hello , " + str;
            return helloMessage;
        }
    }
}

 


如有錯誤 歡迎指正