Lambda 表达式的深化及使用

1.1  Lambda 表达式

1.1.1 创建委托或表达式树

“Lambda 表达式是一个匿名函数,它可以包含表达式和语句,并且可用于创建委托或表达式树类型。

    class Program

    {

        static void Main(string[] args)

        {

            del myDelegate = x => x * x;

            int j = myDelegate(5); //得到j = 25

 

            Console.WriteLine(j);

            Console.Read();

        }

    }

    delegate int del(int i);

    class Program

    {

        static void Main(string[] args)

        {

            Expression<del> myET = x => x * x;

            Console.WriteLine(myET);//得到x => ( x * x )

 

            Console.Read();

        }

    }

    delegate int del(int i);

    class Program

    {

        static void Main(string[] args)

        {

            del myET = new del((x, y) => x + y);

 

            Console.WriteLine(myET(7,8));//15

 

            Console.Read();

        }

    }

    delegate int del(int i,int y);

 

1.2     带有标准查询运算符的 Lambda

许多标准查询运算符都具有输入参数,其类型是泛型委托的 Func<T, TResult> 系列的其中之一。 Func<T, TResult> 委托使用类型参数定义输入参数的数目和类型,以及委托的返回类型。

            Func<int, bool> myFunc = x => x == 5;

            bool result = myFunc(6); //得到false

            Console.WriteLine(result);

            int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 };

            int oddNumbers = numbers.Count(n => n % 2 == 1);//得到5(2取余等于1的数字个数)

            Console.WriteLine(oddNumbers);

1.3     Lambda 表达式创建表达式树

在将 lambda 表达式分配给 Expression<TDelegate> 类型的变量时,编译器将发出代码以生成一个表示 lambda 表达式的表达式树。

            Expression<Func<int, bool>> lambda = num => num < 5;

            Console.WriteLine(lambda);//得到num =>( num < 5 )

 

1.4     API 创建表达式树

            ParameterExpression numParam = Expression.Parameter(typeof(int), "num");

            ConstantExpression five = Expression.Constant(5, typeof(int));

            BinaryExpression numLessThanFive = Expression.LessThan(numParam, five);

            Expression<Func<int, bool>> lambda1 =

                Expression.Lambda<Func<int, bool>>(

                    numLessThanFive,

                    new ParameterExpression[] { numParam });

 

            Console.WriteLine(numParam);//得到num

            Console.WriteLine(five);//5

            Console.WriteLine(numLessThanFive);//得到( num < 5 )

 

1.5  分析表达式树

            Expression<Func<int, bool>> exprTree = num => num < 5;

 

            ParameterExpression param = (ParameterExpression)exprTree.Parameters[0];

            BinaryExpression operation = (BinaryExpression)exprTree.Body;

            ParameterExpression left = (ParameterExpression)operation.Left;

            ConstantExpression right = (ConstantExpression)operation.Right;

 

            Console.WriteLine("Decomposed expression: {0} => {1} {2} {3}",

                              param.Name, left.Name, operation.NodeType, right.Value);

//得到Decomposed expression:num => num LessThan 5

 

1.6  编译表达式树

            Expression<Func<int, bool>> expr = num => num < 5;

            Func<int, bool> result = expr.Compile();

 

            Console.WriteLine(result(4));//True

            Console.WriteLine(expr.Compile()(5));//False

1.7  执行表达式

            BinaryExpression be = Expression.Power(Expression.Constant(2D), Expression.Constant(3D));

            Expression<Func<double>> le = Expression.Lambda<Func<double>>(be);

            Func<double> compiledExpression = le.Compile();

            double result = compiledExpression();

            Console.WriteLine(result);//得到8

posted @   易独  阅读(323)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
乐巴儿 一个有声音的公众号
长按,识别二维码,加关注
点击右上角即可分享
微信分享提示