扩展方法是是定义在静态类内部的静态方法。
如下代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace 扩展方法 8 { 9 class Program 10 { 11 static void Main(string[] args) 12 { 13 string s = "25"; 14 Console.WriteLine(s.Toint());//字符串s直接可以点出Toint()方法。 15 16 Console.ReadKey(); 17 } 18 } 19 public static class EmClass//定义一个静态的类 20 { 21 public static int Toint(this string s)//在静态类里定义静态方法Toint,每个扩展方法的第一个参数必须包含一个this关键字修饰符。 22 { 23 return Int32.Parse(s); 24 } 25 } 26 }
运行结果如下:
原文:http://www.cnblogs.com/qingrenlei/p/3581380.html