C# 扩展方法的使用

c# 扩展方法可以在不继承原有类的基础上,为原有类添加方法,c#扩展方法可以合并到要原有类的实例上,扩展方法需要定义为静态方法,并且第一个参数必须为要扩展类型的当前实例(参数前加this关键字)public static class Extendstring
{
public static string SplitByString(this string str)
{
string strRes;
char[] cs = str.ToArray();
strRes = string.Join(" ", cs);
return strRes;
}
}


首先定义一个静态类,定义一个静态方法,扩展string,第一个参数是 this string str(因为扩展string类所以第一个参数是this string str)函数名为SplitByString

C# 扩展方法的使用
在main函数可以看到string的实例方法有一个扩展方法,即是我们刚刚定义的扩展方法