Lambda表达式演变历史

   /// <summary>
    /// 爬虫委托
    /// </summary>
    /// <param name="crawlerCode">爬虫编码</param>
    delegate void CrawlerDelegate(string crawlerCode);
    class Program
    {
        static void Main(string[] args)
        {
            {
                //.net framework 1.0 最原始
                CrawlerDelegate crawlerDelegate = new CrawlerDelegate(Execute);
                crawlerDelegate.Invoke("爬取第1页");
            }

            {
                //.net framework 2.0 匿名方法
                CrawlerDelegate crawlerDelegate = new CrawlerDelegate(delegate (string crawlerCode) { Console.WriteLine(crawlerCode); });
                crawlerDelegate.Invoke("爬取第2页");
            }

            {
                //.net framework 3.0 Lambda
                CrawlerDelegate crawlerDelegate = new CrawlerDelegate((string crawlerCode) => { Console.WriteLine(crawlerCode); });
                crawlerDelegate.Invoke("爬取第3页");
            }

            {
                //.net framework 3.0 Lambda 参数类型可以省略,参数会被自动推算,俗称“语法糖”
                CrawlerDelegate crawlerDelegate = new CrawlerDelegate((crawlerCode) => { Console.WriteLine(crawlerCode); });
                crawlerDelegate.Invoke("爬取第4页");
            }

            {
                //.net framework 3.0 Lambda 如果方法体只有一行,可以省略大括号和分号
                CrawlerDelegate crawlerDelegate = new CrawlerDelegate((crawlerCode) => Console.WriteLine(crawlerCode));
                crawlerDelegate.Invoke("爬取第5页");
            }

            {
                //.net framework 3.0 Lambda 直接省略创建对象的写法,编译器内部自动波处理
                CrawlerDelegate crawlerDelegate = (crawlerCode) => Console.WriteLine(crawlerCode);
                crawlerDelegate.Invoke("爬取第6页");
            }

            Console.ReadKey();
        }

        /// <summary>
        /// 执行爬虫
        /// </summary>
        /// <param name="crawlerCode">爬虫编码</param>
        private static void Execute(string crawlerCode)
        {
            Console.WriteLine(crawlerCode);
        }

        /// <summary>
        /// 爬虫执行器
        /// </summary>
        /// <param name="crawlerContext">爬虫上下文</param>
        /// <param name="method">爬虫逻辑</param>
        static void CrawlerFerformer(CrawlerContext crawlerContext, CrawlerDelegate method)
        {
            method.Invoke(crawlerContext.CrawlerCode);
        }
    }

    /// <summary>
    /// 爬虫上下文
    /// </summary>
    class CrawlerContext
    {
        /// <summary>
        /// 爬虫编码
        /// </summary>
        public string CrawlerCode { get; set; }
    }

  

posted @ 2019-08-24 14:50  李树逸  阅读(448)  评论(0编辑  收藏  举报