扩展方法
扩展方法:
目的:对已存在的类型的行为进行扩展:
public static class ClassA{ //this keywords is a pointer,表示为string类型定义了一个扩展方法 public static void ExpandMethod(this string s) { //方法体 }}注意事项: 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" }