跳转到内容

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();
    }
}