c# - 如何从 Expression<Func<T, bool>> 谓词中获取属性、运算符和值?

标签 c# linq reflection expression-trees func

有没有办法从 Expression<Func<T>,bool> 中提取属性、运算符和匹配值? ?给定以下示例:

var customers = GetCustomers();
var customerQuery = customers.Where(x=> x.CustomerID == 1 
    && x.CustomerName == "Bob"); // The query is for illustration only

我需要能够得到如下内容:

Property: CustomerID
Operator: Equals
Value:    1

Property: CustomerName
Operator: Equals
Value:    Bob

我已经写了一些可以提取表达式属性名称的东西,但我似乎无法找出值和运算符的保存位置,尽管它在表达式的 DebugView 属性中非常清晰可见。

最佳答案

运算符将在 BinaryExpressionMethod 上,即 Equals 节点。您还应该查看表达式 .NodeType,它揭示了很多(它应该是 Equal)。

通常位于BinaryExpression.Right 中的ConstantExpression 中,或者位于捕获变量的情况:capture-context 将是 ConstantExpression,因此 value 将是 MemberExpressionConstantExpression 上(您需要调查成员是 FieldInfo 还是 PropertyInfo,并通过 .GetValue( ...) 上)。

关于c# - 如何从 Expression<Func<T, bool>> 谓词中获取属性、运算符和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8034126/

相关文章:

c# - 在资源文件中存储包含函数和超链接的大文本

c# - 检查 Collection 中的所有项目是否具有相同的值

c# - 如何访问在运行时定义类型的对象?

java - 为什么隐式转换工作而反射转换抛出异常?

Java 反射 : Get a Field's Value where the Field is of an Interface Type

c# - 如何在 C# 中获取异常错误代码

C# - 如何跳过具有默认值的参数?

c# - 具有聚合函数的 lambda 表达式

c# - 在 View 中创建 HiddenFor IEnumerable<String>

c# - 创建可重用的 Linq 查询