c#编程指南(五) 扩展方法(Extension Method)

C# 3.0就引入的新特性,扩展方法可以很大的增加你代码的优美度,扩展方法提供你扩展.NET Framewoke类的扩展途径,书写和规则也简单的要命。

编写扩展方法有下面几个要求:

第一:扩展方法所在的类必须是全局的,不能是内部嵌套类。

第二:扩展方法的类是静态类。

第三:扩展方法是静态方法。

第四:扩展方法的第一个参数的数据类型必须是要扩展类型。

第五:扩展方法的第一个参数使用this关键字。

下面是一段很简单的代码:

复制代码
1 using System; 2  using System.Collections.Generic; 3  using System.Linq; 4  using System.Text; 5 6  namespace ExtensionMethod 7 { 8 public static class TestClass 9 { 10 public static void Print(this int i) 11 { 12 Console.WriteLine(i); 13 } 14 15 public static int Times(this int i) 16 { 17 return i * 2; 18 } 19 20 public static int Add(this int i, int d) 21 { 22 return i + d; 23 } 24 } 25 26 class Program 27 { 28 static void Main(string[] args) 29 { 30 int number = 4; 31 number.Print(); 32 Console.WriteLine(number.Times()); 33 Console.WriteLine(number.Add(5)); 34 } 35 } 36 }
复制代码

代码很简单,扩展的是int类型。

第一个是定义了一个Print方法,是没有参数没有返回值的扩展方法。

第二个是定义了一个带返回值无参数的扩展方法。

第三个是定义了一个有返回值有参数的扩展方法。

原文地址:https://www.cnblogs.com/xbzhu/p/7381386.html