开发者

.net lambda expression casting

开发者 https://www.devze.com 2023-02-02 19:35 出处:网络
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

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.Documen开发者_高级运维t

Is that possible?


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);
0

精彩评论

暂无评论...
验证码 换一张
取 消