扩展方法的理解

以前以为扩展方法有多难,所以没有动笔写东西,今天刚好休息,所以自己练练拓展方法,其实很简单,建议读者也自己写一个然后用反编译工具看看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();
        }
    }

原来扩展方法就是一个静态类,在方法里面调用该静态类的静态方法而已,现在应该理解扩展方法的条件了吧

 







  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值