C# 扩展方法

来源:互联网 发布:网络聊天技巧话术 编辑:程序博客网 时间:2024/05/21 11:05

使用 .net  3.0之后,我一直都觉得有种方法很奇怪,这种方法在一般的方法前面多了一个蓝色的向下箭头。

这种方法其实是扩展方法,这种扩展方法不需要去修改原类。

class Program{    static void Main(string[] args)    {        string re = "";        while ((re = Console.ReadLine()) != "exit")        {            Console.WriteLine(re.InsteadString());        }    }}public static class ExtendFunction{    public static string InsteadString(this string inputString)    {        return inputString + "<End>";    }} 

例子中我定义了一个扩展方法,这个方法是为string类型扩展的,注意参数列表,this Type object,Type就是你要扩展的类型。

扩展方法必须注意几点:

1.扩展方法必须在一个静态的非泛型类中。

2.扩展方法本身必须为静态。

3.扩展方法必须包含一个参数,也就是指定扩展的类型,而且方法的第一个参数必须是指定扩展的类型,这个参数被称为实例参数。

4.实例参数必须并且只能由this修饰。

 

终于搞明白了为什么linq中的一些方法可以被其他的泛型类所使用了。