.net lambda 表达式转换
也许我想要实现的目标是无意义的,但我认为它应该有效。 我有一个表达式,
Expression<Func<Model.Document, bool>> expr1 = d => //something
我需要将此表达式转换为
Expression<Func<Model.Invoice, bool>
Model.Invoice 继承自 Model.Document 的位置,
这可能吗?
maybe what I'm trying to achieve is a non-sense, but I think it should work.
I have an expression
Expression<Func<Model.Document, bool>> expr1 = d => //something
I nedd to cast this Expression in a
Expression<Func<Model.Invoice, bool>
where Model.Invoice inherits from Model.Document
Is that possible?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这实际上与 lambda 表达式无关 - 它与表达式树尤其是
Expression
有关。Expression
在 T 中是不变的 - 即使不是,Func
和Func
不适合协方差,除非我弄错了(这很有可能)。我怀疑您需要分解
Expression
并重新创建它,这可能不是很简单......或者您可以在周围添加一个包装层现有的Expression
,这半等价于:This isn't really to do with lambda expressions - it's to do with expression trees and
Expression<TDelegate>
in particular.Expression<TDelegate>
is invariant in T - and even if it weren't, the relationship betweenFunc<Model.Document, bool>
andFunc<Model.Invoice, bool>
wouldn't be appropriate for covariance, unless I'm mistaken (which is quite possible).I suspect you'll need to break up the
Expression<T>
and recreate it, which may not be terribly simple... alternatively you could add a wrapper layer around the existingExpression<T>
, which would be semi-equivalent to saying: