以前以为扩展方法有多难,所以没有动笔写东西,今天刚好休息,所以自己练练拓展方法,其实很简单,建议读者也自己写一个然后用反编译工具看看IL代码。
先上例子:
namespace 扩展方法 { class Program { static void Main(string[] args) { List<int> list = new List<int> { 1, 2, 3, 7, 5, 8, 4 }; list = list.SortBigerThree(); foreach (var item in list) { Console.WriteLine(item); } Console.ReadKey(); } } public static class ExList { public static List<int> SortBigerThree(this List<int> list) { List<int> myList = new List<int> { }; list.Sort(); foreach (var item in list) { if (item > 3) { myList.Add(item); } } return myList; } } }我们知道list是没有SortBigerThree方法,但是list调用起来和自己的方法一样,再看看msdn,扩展方法的条件,静态类,静态方法,以及静态方法中的第一个参数this。
我们一起看看IL代码吧
红色的地方我标注起来了,我们一看就明白了,原理编译器在后面帮我们做了工作,其实上面的代码等价于以下代码:
class Program { static void Main(string[] args) { List<int> list = new List<int> { 1, 2, 3, 7, 5, 8, 4 }; //list = list.SortBigerThree(); list = ExList.SortBigerThree(list); foreach (var item in list) { Console.WriteLine(item); } Console.ReadKey(); } }
原来扩展方法就是一个静态类,在方法里面调用该静态类的静态方法而已,现在应该理解扩展方法的条件了吧