有没有办法从 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 属性中非常清晰可见。
最佳答案
运算符将在 BinaryExpression
的 Method
上,即 Equals
节点。您还应该查看表达式 .NodeType
,它揭示了很多(它应该是 Equal
)。
值 通常位于BinaryExpression
的.Right
中的ConstantExpression
中,或者位于捕获变量的情况:capture-context 将是 ConstantExpression
,因此 value 将是 MemberExpression
在 ConstantExpression
上(您需要调查成员是 FieldInfo
还是 PropertyInfo
,并通过 .GetValue( ...)
上)。
关于c# - 如何从 Expression<Func<T, bool>> 谓词中获取属性、运算符和值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8034126/