CS3L10——拓展方法
拓展方法
拓展方法可以为现有的 非静态变量类型 添加 新办法
作用:
- 提升代码拓展性
 
- 不需要在在对象中重新写办法
 
- 不需要继承来添加方法
 
- 为别人封装的类型写额外的方法
 
特点:
- 一定是写在静态类中
 
- 一定是个静态函数
 
- 第一个参数为拓展目标
 
- 第一个参数用 
this 修饰 
拓展方法可以有返回值 和 n 个参数根据需求而定
基本语法
1
   | 访问修饰符 static 返回值 函数名(this 被拓展的类名 参数名, 参数类型 参数名, 参数类型 参数名,...) { }
  | 
 
拓展示例
假设要为 int 和 string 拓展一个成员方法,成员方法 是需要 实例化对象后 才能使用的,
第一个参数 是规定为了哪一个非静态的变量类型添加拓展方法,使用这个方法的是 哪个对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
   | static class Tools {               public static void SpeakValue(this int value)     {                  Console.WriteLine("MrTang对int拓展的方法");     }     public static void SpeakStringInfo(this string str, string str2, string str3)     {         Console.WriteLine("MrTang对string拓展的方法");         Console.WriteLine("调用方法的对象是:" + str);         Console.WriteLine("传的参数是:" + str2 + str3);     } }
  internal class Program {     static void Main(string[] args)     {         int i = 10;         i.SpeakValue();
          string str = "调用拓展方法的字符串的内容";         str.SpeakStringInfo("C# ", "is good");     } }
   | 
 
输出:
1 2 3 4
   | MrTang对int拓展的方法 MrTang对string拓展的方法 调用方法的对象是:调用拓展方法的字符串的内容 传的参数是:C# is good
   | 
 
为自定义的类型拓展方法
注意!如果 拓展方法 与 被拓展的类里面的方法 重名 且没有重载该方法,则会优先调用类里面的方法 拓展方法就会失效!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
   | class Test {     public int i = 10;     public void Fun1()     {         Console.WriteLine("123");     }
      public void Fun2()     {         Console.WriteLine("456");     } }
  static class Tools {     public static void Fun3(this Test t)     {         Console.WriteLine("为test拓展的方法");     }
      public static void Fun2(this Test t)     {         Console.WriteLine("为test拓展的方法2");     }
           public static void Fun2(this Test t, int t2)     {         Console.WriteLine("为test拓展的方法" + t2);     } }
  internal class Program {     static void Main(string[] args)     {         Test t = new Test();         t.Fun1();         t.Fun2();         t.Fun2(2);         t.Fun3();     } }
   | 
 
输出:
1 2 3 4
   | 123 456                     为test拓展的方法2 为test拓展的方法
   |