03、扩展方法
1)扩展方法就是通过对原有的类型在不修改原来代码的情况下,添加方法的过程。
1 class Program 2 { 3 //扩展方法知识看起来像是调用了某个对象的方法,但实际上根本不是该对象的方法,实际上就是调用了某个静态类中的方法。 4 static void Main(string[] args) 5 { 6 Person p = new Person(); 7 p.Name = "zhangsan"; 8 p.sayHello();//输出zhangsan 9 10 //给string添加扩展方法 11 string s = "abcde"; 12 Console.WriteLine(s.count());//输出5 13 } 14 } 15 //扩展方法第一步:定义一个静态类 16 public static class ExtensionMethod 17 { 18 //this Person person 表示给Person类添加扩展方法 19 public static void sayHello(this Person person) 20 { 21 Console.WriteLine(person.Name); 22 } 23 public static int count(this string s) 24 { 25 return s.ToCharArray().Length; 26 } 27 } 28 public class Person 29 { 30 public string Name { get; set; } 31 public void smile() 32 { 33 Console.WriteLine("hahaha"); 34 } 35 }