给定一个接受识别对象并返回属性的 lambda:
Expression<Func<Identification, object>> fx = _ => _.Id;
以及将对象转换为识别实例的转换 lambda:
ParameterExpression p = Expression.Parameter(typeof(object), "o");
Expression @new = Expression.Lambda(Expression.Convert(p, typeof(Identification)), p);
如何构建一个执行 @new
的新 lambda(获取识别)实例)并将结果传递到fx
。我需要 @new 的结果以某种方式绑定到 fx 的第一个参数,但我找不到示例。
我需要结果为 Expression
,它的类型应为 Expression>
并且应将入站参数转换为 识别
,然后获取Id
属性。
Given a lambda that takes an Identification object, and returns a property:
Expression<Func<Identification, object>> fx = _ => _.Id;
And a conversion lambda that converts an object into an Identification instance:
ParameterExpression p = Expression.Parameter(typeof(object), "o");
Expression @new = Expression.Lambda(Expression.Convert(p, typeof(Identification)), p);
How do I build a new lambda that executes @new
(getting out the Identification Instance) and passes the result into fx
. I need @new
's result to bind to the first parameter of fx
somehow, and I cannot find an example.
I need the result to be an Expression
, it should be of type Expression<Func<object, object>>
and it should convert the inbound parameter to an Identification
and then get the Id
property.
发布评论
评论(2)
首先,请注意,如果您正确键入
@new
,这会更容易,即:因为这样可以轻松访问
@new.Body
和@new.Parameters;做到了,
Expression.Invoke
在这里很有用:尽管对于更清晰的表达式,您也可以使用
ExpressionVisitor
完全替换内部表达式:with:
这样做的作用是:
@new.Body
替换_
(参数)的所有实例(请注意,这将包含对_
的引用) code>o 参数(又名p
)@new
中的相同参数,这确保我们注入的值将被正确绑定Firstly, note that this is easier if you type
@new
appropriately, i.e.:since that provides easy access to
@new.Body
and@new.Parameters
; that done,Expression.Invoke
can be useful here:although for a cleaner expression, you can also use
ExpressionVisitor
to completely replace the inner expressions:with:
what this does is:
fx.Body
tree, replacing all instances of_
(the parameter) with the@new.Body
(note that this will contain references to theo
parameter (akap
)@new
, which ensures that the values we injected will be bound correctly使用 Marc Gravell 的答案中的代码,您可以通过辅助函数很好地简化此操作:
现在看看它有多干净!
它可以与实体框架和其他需要干净的
Expression
的东西一起使用,而不会尝试调用其中的Func
。Using the code from Marc Gravell's answer, you can simplify this really nicely with a helper function:
Now look how clean that is!
And it works with Entity Framework and other things that need a clean
Expression
that doesn't try to invoke aFunc
within it.