[size=large]扩展方法:
目的:对已存在的类型的行为进行扩展:[/size]
扩展方法是一种特殊的静态方法
扩展方法必须在静态类中定义
扩展方法的优先级低于同名的类方法
扩展方法只能在特定的命名空间中有效
排除必需不要滥用扩展方法
LinQ中的绝大数方法都是扩展方法[/size]
示例:
//静态类
目的:对已存在的类型的行为进行扩展:[/size]
public static class ClassA
{
//this keywords is a pointer,表示为string类型定义了一个扩展方法
public static void ExpandMethod(this string s)
{
//方法体
}
}
[size=large]注意事项:
扩展方法是一种特殊的静态方法
扩展方法必须在静态类中定义
扩展方法的优先级低于同名的类方法
扩展方法只能在特定的命名空间中有效
排除必需不要滥用扩展方法
LinQ中的绝大数方法都是扩展方法[/size]
示例:
//静态类
public static class ExpandClss
{
//静态类中的拓展方法
public static string ExtraMethodToString(this string s)
{
return s.Substring(0, 1).ToUpper() + s.Substring(1);
}
//带参数的拓展方法
public static string ExtraMethodToString(this string s,int len)
{
return s.Substring(0, 1).ToUpper() + s.Substring(1,len);
}
}
//使用静态类
private void button1_Click(object sender, EventArgs e)
{
string s = "abcdefgafateateaft";
//要求首字母大写,其它字母小写,使用拓展方法实现
Console.WriteLine(s.ExtraMethodToString());
//output result "Abcdefgafate"
Console.WriteLine(s.ExtraMethodToString(4));
//output result "Abcd"
}