我可以使用 LINQ 表达式参数化 PropertyExpression 的属性名称吗?
假设我有以下 LambdaExpression:
var itemParam = Expression.Parameter(typeof(Thing), "thing");
var someValue = "ABCXYZ123"; // value to compare
LambdaExpression lex = Expression.Lambda(
Expression.Equal(
Expression.Property(itemParam, "Id"), // I want ID to be a Body expression parameter
Expression.Constant(someValue)
), itemParm);
并且我希望将 Expression.Property(...) 工厂中的属性名称(第二个参数)作为参数,我该如何执行此操作?
我希望看到一个看起来像这样的构造函数,但它不存在:
Expression.Property(Expression instance, Expression propName)
是否有一些我可以使用的技巧,可以将参数化的 ConstantExpression 转换为所需的字符串或会员信息?也许我的处理方式是错误的。
我的预感是,由于这些表达式树在编译时会成为轻量级 IL,因此需要成员访问信息,因此在构造表达式树时必须提供成员和属性的名称。
感谢您的任何提示!
编辑:想补充一点,这将用作 Enumerable.Where(...) 扩展方法的参数,用于确定两个类/实体之间关系的匹配。
Supposing I have the following LambdaExpression:
var itemParam = Expression.Parameter(typeof(Thing), "thing");
var someValue = "ABCXYZ123"; // value to compare
LambdaExpression lex = Expression.Lambda(
Expression.Equal(
Expression.Property(itemParam, "Id"), // I want ID to be a Body expression parameter
Expression.Constant(someValue)
), itemParm);
And I want the property name (2nd parameter) in the Expression.Property(...) factory to be a parameter, how do I go about doing this?
I was hoping to see a constructor that looks like this, but it doesn't exist:
Expresssion.Property(Expression instance, Expression propName)
Is there some trick I can pull that can convert a parameterized ConstantExpression into the needed string or MemberInfo? Maybe I'm going about this the wrong way.
My hunch is that because these expression trees, when compiled, become lightweight IL, that member access information is required, thus, the names of members and properties must be provided when constructing expression trees.
Thanks for any tips!!
EDIT: Wanted to add that this will be used as an argument to the Enumerable.Where(...) extension method for determining a match on a relationship between two classes / entities.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
表达式树表示的 IL 结构大致与您在 C#/VB.NET 程序中看到的类型相同。您无法参数化该属性表达式,其原因与您无法“参数化”以下代码的原因相同:
如果您需要实现此功能,并且您的表达式树未传递给
IQueryable
,您可以编写一个辅助函数,它接受一个对象和一个字符串,并返回由该字符串标识的该对象的属性值;然后您可以使用Expression.Call
将该辅助函数调用到您正在构建的表达式树中。Expression trees represent IL structures that are roughly of the same kind that you see in your C#/VB.NET programs. You cannot parameterize that property expression for the same reason that you cannot "parameterize" the following code:
If you need to implement this functionality, and your expression trees are not passed to
IQueryable<T>
, you can write a helper function taking an object and a string, and returning value of that object's property identified by the string; then you can useExpression.Call
to invoke that helper function into the expression tree that you are building.