慕尼黑8549860
可以使用表达式访问器替换该类型。class ParameterRewriter<T, U> : ExpressionVisitor{ protected override Expression VisitParameter(ParameterExpression node) { if (node.Type.Equals(typeof(T))) { return Expression.Parameter(typeof(U), node.Name); } return base.VisitParameter(node); } protected override Expression VisitMember(MemberExpression node) { if (node.Expression is ParameterExpression paramExp && paramExp.Type.Equals(typeof(T))) { return Expression.MakeMemberAccess( Expression.Parameter(typeof(U), paramExp.Name), typeof(U).GetMember(node.Member.Name).Single()); } return base.VisitMember(node); } protected override Expression VisitLambda<L>(Expression<L> node) { var parameters = node.Parameters.ToList(); var found = false; for (var i = 0; i < parameters.Count; i++) { if (parameters[i].Type.Equals(typeof(T))) { parameters[i] = Expression.Parameter(typeof(U), parameters[i].Name); found = true; } } if (found) { return Expression.Lambda(node.Body, parameters); } return base.VisitLambda(node); }}在这种情况下,创建一个实例并访问原始表达式树,您将获得所需的内容。扩展方法可能更具可读性:new ParameterRewriter<DocumentTypeA, DocumentTypeB>()public static class ExpressionExtensions{ public static Expression<Func<U, R>> RewriteParameter<T, U, R>(this Expression<Func<T, R>> expression) { var rewriter = new ParameterRewriter<T, U>(); return (Expression<Func<U, R>>)rewriter.Visit(expression); }}用法很简单:Expression<Func<A, bool>> expA = x => x.Id == 1;Expression<Func<B, bool>> expB = expA.RewriteParameter<A, B, bool>();