C Sharp/Extension methods

擴展方法是C# 3.0引入的特性。允許你寫自己的方法擴展類的方法。但擴展方法不能訪問類的私有或保護的方法、屬性、字段。

擴展方法必須聲明在靜態類的靜態方法,至少一個參數指出該擴展方法適用的類。

public static class MyExtensions
{
    public static string[] ToStringArray<T>(this List<T> list)
    {
        string[] array = new string[list.Count];

        for (int i = 0; i < list.Count; i++)
            array[i] = list[i].ToString();

        return array;
    }

    // to be continued...
}

調用該擴展方法:

List<int> list = new List<int>();

list.Add(1);
list.Add(2);
list.Add(3);

string[] strArray = list.ToStringArray(); // strArray will now contain "1", "2" and "3".


using System;
using System.Collections.Generic;

public static class MyExtensions
{
    ... // continued from above

    public static void WriteToConsole(this string str)
    {
        Console.WriteLine(str);
    }

    public static string Repeat(this string str, int times)
    {
        System.Text.StringBuilder sb = new System.Text.StringBuilder();

        for (int i = 0; i < times; i++)
            sb.Append(str);

        return sb.ToString();
    }
}

class ExtensionMethodsDemo
{
    static void Main()
    {
        List<int> myList = new List<int>();
        
        for (int i = 1; i <= 10; i++)
            myList.Add(i);
        
        string[] myStringArray = myList.ToStringArray();
        
        foreach (string s in myStringArray)
            s.Repeat(4).WriteToConsole(); // string is extended by WriteToConsole()
        
        Console.ReadKey();
    }
}