C#语言从3.0开始增加了一个很特别的功能:扩展方法。
那么扩展方法起什么作用呢?很多时候我们想为已经存在的类扩展某些功能,而又没有必要去继承该类,甚至有时候这个类根本就不允许继承,如String类,这时候就可以使用扩展方法来为其扩展功能。
下面举例说明:
一、我们创建一个类库如下:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace MethodExtendClasses
{
//此类本身不起什么作用,只是在运行时将方法加载到内存中
public static class ExtendsString
{
//用this关键字修饰了string 关键字,表示这个方法是string的扩展方法
public static string SpaceToUnderLine(this string source)
{
char[] chars = source.ToCharArray();
string temp = "";
foreach (char c in chars)
{
if (char.IsWhiteSpace(c))
temp += "_";
else
temp += c;
}
return temp;
}
}
}
然后编译。
二、创建一个测试用的控制台程序,添加上一个项目的引用,然后将代码修改如下:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MethodExtendClasses;//此名称空间为扩展方法所在位置
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string str = "abc dd tt";
str = str.SpaceToUnderLine(); //SpaceToUnderLine()方法就是我们为string增加的扩展方法,此时看起来好像string类多了个方法,其实我们并没有真正的操作string类
Console.WriteLine(str);
}
}
}
编译运行,结果为:abc_dd_tt。说明SpaceToUnderLine()方法起到了作用。
总结
我们在进行方法扩展时,需要注意以下几点:
1. 扩展方法所在类必须是静态的。
2. 扩展方法必须是静态的。
3.扩展方法的参数类型必须是要扩展的类型。
4. 参数类型前必须要加this关键字。
转自:http://student.csdn.net/space.php?uid=270457&do=blog&id=43384