了解C#的Expression
我们书接上文,我们在了解LINQ下面有说到在本地查询IEnumerbale主要是用委托来作为传参,而解析型查询
IQueryable则用Expression来作为传参:
public static IEnumerable<T> Where<T>(this IEnumerable<T> enumable, Func<T, bool> func)
public static IQueryable<T> Where<T>(this IQueryable<T> queryable, Expression<Func<T, bool>> func)
那么我们就来聊聊有关表达式Expression里面的东西吧
Expression与Expression Tree
首先我们来写下一些代码:
Expression<Func<int, int>> expression = (num) => num + 5;
Console.WriteLine($"NodeType:{expression.NodeType}");
Console.WriteLine($"Body:{expression.Body}");
Console.WriteLine($"Body Type: {expression.Body.GetType()}");
Console.WriteLine($"Body NodeType: {expression.Body.NodeType}");
输出如下:
NodeType:Lambda
Body:(num + 5)
Body Type: System.Linq.Expressions.SimpleBinaryExpression
Body NodeType: Add
我们将expression
转为LambdaExpression
看看都有啥:
if (expression.NodeType == ExpressionType.Lambda)
{
var lambda = (LambdaExpression)expression;
var parameter = lambda.Parameters.Single();
Console.WriteLine($"parameter.Name:{parameter.Name}");
Console.WriteLine($"parameter.Type:{parameter.Type}");
Console.WriteLine($"parameter.ReturnType:{lambda.ReturnType}");
}
输出如下:
parameter.Name:num
parameter.Type:System.Int32
parameter.ReturnType:System.Int32
由于我们知道expression.Body
是BinaryExpression
,那么我们就将其转为它,然后我们继续看下去:
if (expression.Body.NodeType == ExpressionType.Add)
{
var binaryExpreesion = (BinaryExpression)expression.Body;
Console.WriteLine($"Left Type:{binaryExpreesion.Left.GetType()}");
Console.WriteLine($"Left NodeType:{binaryExpreesion.Left.NodeType}");
Console.WriteLine($"Right Type:{binaryExpreesion.Right.GetType()}");
Console.WriteLine($"Right NodeType:{binaryExpreesion.Right.NodeType}");
if (binaryExpreesion.Left is ParameterExpression parameterExpreesion)
{
Console.WriteLine($"parameterExpreesion.Name:{parameterExpreesion.Name}");
Console.WriteLine($"parameterExpreesion.Type:{parameterExpreesion.Type}");
}
if (binaryExpreesion.Right is ConstantExpression constantExpreesion)
{
Console.WriteLine($"constantExpreesion.Value:{constantExpreesion.Value}" );
}
}
输出如下:
Left Type:System.Linq.Expressions.PrimitiveParameterExpression`1[System.Int32]
Left NodeType:Parameter
Right Type:System.Linq.Expressions.ConstantExpression
Right NodeType:Constant
parameterExpreesion.Name:num
parameterExpreesion.Type:System.Int32
constantExpreesion.Value:5
最后我们将表达式树转为委托:
var @delegate = expression.Compile();
Console.WriteLine(@delegate?.Invoke(2));
输出:
7 //2+5
实际上,通过Expression<Func<int, int>> expression = (num) => num + 5;
,赋值后的expression
变成了一个表达式树,它的结构是这样的:
而有意思的是二元表达式树BinaryExpression
是一个二叉树,而LambdaExpression则是一个支持参数的表达式,能够通过其Parameters
属性知道传入的参数的类型和数量,通过ReturnType
知道返回值是什么类型
而我们再看看整个关于Expression
的继承关系链:
因此,我们也可以显式的通过各自Expreesion的实现子类来创建跟lambda表达式一样的结果:
var parameterExpreesion1 = Expression.Parameter(typeof(int), "num");
BinaryExpression binaryExpression1 = Expression.MakeBinary(ExpressionType.Add, parameterExpreesion1, Expression.Constant(5));
Expression<Func<int, int>> expression1 = Expression.Lambda<Func<int, int>>(binaryExpression1, parameterExpreesion1);
if (expression1.Body.NodeType == ExpressionType.Add)
{
var binaryExpreesion1 = (BinaryExpression)expression1.Body;
Console.WriteLine($"Left Type:{binaryExpreesion1.Left.GetType()}");
Console.WriteLine($"Left NodeType:{binaryExpreesion1.Left.NodeType}");
Console.WriteLine($"Right Type:{binaryExpreesion1.Right.GetType()}");
Console.WriteLine($"Right NodeType:{binaryExpreesion1.Right.NodeType}");
if (binaryExpreesion1.Left is ParameterExpression parameterExpreesion2)
{
Console.WriteLine($"parameterExpreesion.Name:{parameterExpreesion2.Name}");
Console.WriteLine($"parameterExpreesion.Type:{parameterExpreesion2.Type}");
}
if (binaryExpreesion1.Right is ConstantExpression constantExpreesion1)
{
Console.WriteLine($"constantExpreesion.Value:{constantExpreesion1.Value}");
}
var @delegate1 = expression1.Compile();
Console.WriteLine(@delegate1(2));
输出结果:
Left Type:System.Linq.Expressions.PrimitiveParameterExpression`1[System.Int32]
Left NodeType:Parameter
Right Type:System.Linq.Expressions.ConstantExpression
Right NodeType:Constant
parameterExpreesion.Name:num
parameterExpreesion.Type:System.Int32
constantExpreesion.Value:5
result:7
我们则发现,结果是一模一样的,但是费劲了很多,因此用lamda构建表达式树是一个非常愉快的语法糖,让你能够愉快的在使用表达式和表达式树
参考
- 《C#7.0核心技术指南》
源码
了解C#的Expression的更多相关文章
- AutoMapper:Unmapped members were found. Review the types and members below. Add a custom mapping expression, ignore, add a custom resolver, or modify the source/destination type
异常处理汇总-后端系列 http://www.cnblogs.com/dunitian/p/4523006.html 应用场景:ViewModel==>Mode映射的时候出错 AutoMappe ...
- OpenCASCADE Expression Interpreter by Flex & Bison
OpenCASCADE Expression Interpreter by Flex & Bison eryar@163.com Abstract. OpenCASCADE provide d ...
- Expression Blend创建自定义按钮
在 Expression Blend 中,我们可以在美工板上绘制形状.路径和控件,然后修改其外观和行为,从而直观地设计应用程序.Button按钮也是Expression Blend最常用的控件之一,在 ...
- [C#] C# 知识回顾 - 表达式树 Expression Trees
C# 知识回顾 - 表达式树 Expression Trees 目录 简介 Lambda 表达式创建表达式树 API 创建表达式树 解析表达式树 表达式树的永久性 编译表达式树 执行表达式树 修改表达 ...
- Could not evaluate expression
VS15 调试变量不能显示值,提示:Could not evaluate expression 解决办法: 选择"在调试时显示运行以单击编辑器中的按钮"重启VS即可. 可参考:Vi ...
- 使用Expression实现数据的任意字段过滤(1)
在项目常常要和数据表格打交道. 现在BS的通常做法都是前端用一个js的Grid控件, 然后通过ajax的方式从后台加载数据, 然后将数据和Grid绑定. 数据往往不是一页可以显示完的, 所以要加分页: ...
- 使用Expression实现数据的任意字段过滤(2)
上一篇<使用Expression实现数据的任意字段过滤(1)>, 我们实现了通过CriteriaCollectionHandler对象来处理集合数据过滤.通过适当的扩展, 应该可以满足一般 ...
- React Native JSX value should be expression or a quoted JSX text.
问题描述: 我在使用props时候, 我的写法是这样的 ... <View> <Person name='john' age=32 gender=true></Pers ...
- [LeetCode] Ternary Expression Parser 三元表达式解析器
Given a string representing arbitrarily nested ternary expressions, calculate the result of the expr ...
- [LeetCode] Regular Expression Matching 正则表达式匹配
Implement regular expression matching with support for '.' and '*'. '.' Matches any single character ...
随机推荐
- [loj2469]最小方差生成树
2018年论文题 约定:令点集$V=[1,n]$.边集$E=[1,m]$,记$m$条边依次为$e_{i}=(x_{i},y_{i},c_{i})$(其中$1\le i\le m$),将其按照$c_{i ...
- [poj2505]A multiplication game
首先有SG(k)=mex(SG(k/2),SG(k/3)--SG(k/9)),SG(0)=0,通过打表可以发现当$n\in[1,1]\cup [10,18]\cup [163,324]--$,规律大概 ...
- [bzoj1101]Zap
1 #include<bits/stdc++.h> 2 using namespace std; 3 #define N 50001 4 int t,n,m,k,ans,mu[N],vis ...
- [cf1491I]Ruler Of The Zoo
为了统一描述,下面给出题意-- 有$n$只动物,编号为$i$的动物有属性$a_{i,j}$($0\le i<n,0\le j\le 2$) 初始$n$只动物从左到右编号依次为$0,1,...,n ...
- [loj2461]完美的队列
参考论文,这里一共写了论文中的3种做法,第一种做法为强制在线时的做法,第二种为时间复杂度略高的做法(前两种都无法通过),第三种为本题正解,并给出了一种理论复杂度更优的做法 1.做法1 情况1 $\fo ...
- 力扣 - 剑指 Offer 27. 二叉树的镜像
题目 剑指 Offer 27. 二叉树的镜像 思路1(递归) 我们可以使用深度优先搜索,先递归到链表的末尾,然后从末尾开始两两交换.就相当于后续遍历而已 记得要先保存下来node.right节点,因为 ...
- SSM(Spring-MyBatis-SpringMVC)框架整合【完整版】
整合SSM 01 基本配置文件的关系 web.xml配置DispatcherServlet 02 需要的maven依赖 <!--依赖 1.junit 2.数据库连接池 3.servlet 4.j ...
- Codeforces 730L - Expression Queries(大模拟)
Codeforces 题面传送门 & 洛谷题面传送门 大模拟(?)+阿巴细节题,模拟赛时刚了 3h 最后因为某个细节写挂 100->40/ll/ll(下次一定不能再挂分了啊 awa) 首 ...
- R语言hist重叠图作法
set.seed(1) h1<-hist(rnorm(1000,100,5)) h2<-hist(rnorm(1000,99,5)) plot(h2,col=rgb(255,0,0,50, ...
- python—模拟生成双色球号
双色球规则:"双色球"每注投注号码由6个红色球号码和1个蓝色球号码组成.红色球号码从1--33中不重复选择:蓝色球号码从1--16中选择. # -*- coding:UTF-8 - ...