.net lambda 表达式转换

发布于 2024-10-10 06:55:29 字数 299 浏览 1 评论 0原文

也许我想要实现的目标是无意义的,但我认为它应该有效。 我有一个表达式,

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

看海 2024-10-17 06:55:29

这实际上与 lambda 表达式无关 - 它与表达式树尤其是 Expression 有关。 Expression 在 T 中是不变的 - 即使不是,FuncFunc 不适合协方差,除非我弄错了(这很有可能)。

我怀疑您需要分解 Expression 并重新创建它,这可能不是很简单......或者您可以在周围添加一个包装层现有的Expression,这半等价于:

 Expression<Func<Invoice, bool>> = invoice => (d => ...)(invoice);

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 between Func<Model.Document, bool> and Func<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 existing Expression<T>, which would be semi-equivalent to saying:

 Expression<Func<Invoice, bool>> = invoice => (d => ...)(invoice);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文