c#进阶学习--委托2(匿名方法与lamdba表达式)

参考资料:深入理解c#

委托1:https://blog.csdn.net/why070809123/article/details/102492612

一、概述

 在上一篇博客里面已经叙述了委托的基础用法,本篇主要叙述委托的进一步用法,以及他是如何一步步变成lambda表达式的。

 

二、委托的变化过程

普通的委托应用:

        delegate string delTest(string input);
        public static string tes(string input)
        {
            string output = "输出" + input;
            return output;
        }
        static void Main(string[] args)
        {
            delTest del = new delTest(tes);
        }

我们需要提前写出方法,并将方法给到相应的委托,c#语言为了方便我们的代码编写工作,可以不用提前创建方法, 在实例化委托的时候给出临时的方法就可以了

匿名方法的应用:

        delegate string delTest(string input);
        static void Main(string[] args)
        {
            delTest del = delegate(string input) { string output = "输出" + input; return output; };
        }

匿名方法的进一步变化:

        delegate string delTest(string input);
        static void Main(string[] args)
        {
            delTest del = (input) =>{ string output = "输出" + input; return output; };
        }

继续变:

        delegate string delTest(string input);
        static void Main(string[] args)
        {
            delTest del = input => "输出" + input ;
        }

三.委托变换(lambda表达式)的应用

应用代码:

   class 测试
    {
        public delegate int nowDate(测试 obj);
        public int agex = 10;
        public int birthday = 2019;
        public int getNowDage(nowDate i)
        {
            return i(this);
        }
        static void Main(string[] args)
        {
            测试 t1 = new 测试() { agex = 25, birthday = 1994 };
            int age = t1.getNowDage((i) => i.birthday + i.agex);
            Console.WriteLine(age);
        }
    }

结果:

 

lambda在c#源码中的应用:

得到list中所有的偶数:

List<int> intTestList = new List<int>() { 1, 2, 3, 4, 5,6,7,8,9,10 };
List<int> testResult = intTestList.Where((x1) => x1 % 2 == 0).ToList();

c#list.where 方法的源码:

public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate);

该方法为迭代器的扩展方法,List继承自迭代器所以可以调用。

public class List<T> : IList<T>, ICollection<T>, IList, ICollection, IReadOnlyList<T>, IReadOnlyCollection<T>, IEnumerable<T>, IEnumerable

参数为Func的委托,同样看一下源码(这里用到泛型后面会进行详细讲解)

  public delegate TResult Func<in T, out TResult>(T arg);

结合where方法及其调用可知,输入的为bool类型,输出为int类型的迭代,从而得到结果。

至于where方法中的委托使用细节就看不了了。。。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

why070809123

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值