首页 > 技术文章 > 扩展方法

jizhiqiliao 2018-10-19 10:29 原文

扩展方法使你能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。 扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。

创建扩展方法的先决条件如下,扩展方法必须定义在一个非嵌套、非泛型的静态类中,扩展方法必须声明为静态,扩展发放至少拥有一个参数(即调用者本身),第一个参数要以 this 关键字作为前缀,在参数列表中不能有其他修饰符(如 ref,out)。

以下代码展示了如何为 string 类型创建一个扩展方法实现添加尾缀“ing”:

static class Test
{
    public static string AddSuffix(this string str, int i)
    {
        return string.Format("{0}ing {1} projects", str, i);
    }
}

以下代码定义一个字符串变量,并用其调用新建扩展方法:

class Program
{
    static void Main()
    {
        string str = "do";
        string newstr = str.AddSuffix(2);
        Console.WriteLine(newstr);
        Console.ReadKey();
    }
}

输出结果如下:

doing 2 projects

推荐阅读