![](/img/trans.png)
[英]How to convert Linq Expression<Func<object,object,bool>> to Expression<Func<T1,T2,bool>>
[英]How to convert Expression<Func<T1, bool>> to Expression<Func<T2, bool>>
我需要轉換表達式
來自: Expression<Func<T1, bool>>
到: Expression<Func<T2, bool>>
由於T1
和T2
可以不同,所以我知道需要重新創建該表達式。 我希望有一個小的方法可以重用於多個對象。
在一般情況下這是不可能的。 這是一個簡單的例子來說明我的觀點:
class Apple {
public int Weight {get;set;}
}
class Orange {
public int Diameter {get;set;}
}
Expression<Func<Apple,bool>> heavy = a => a.Weight > 250;
即使遍歷“ heavy
的表達樹,也無法將“ Apple
Weight
”轉換為與“ Orange
相關的任何東西。
表達式中僅適用於Apple
調用方法會出現類似的問題。
在有限的情況下,當T1
上的表達式僅限於T2
可用的成員時,您可以使用ExpressionVisitor
類進行轉換。 覆蓋VisitMember
,檢查T1
MemberExpression node
的內容,在T2
找到一個對應的成員,並構造替換的Expression
。 對於使用在DTO上構造的表達式查詢后端DB而言,這可能是一個可行的技巧。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.