我找不到从Expression
public object Convert(Expression<Func<T1,bool>> expr, Type t);
T2由T1
导出public class T1 {
int FamilyId {get; set;}
}
public class T2 : T1 {
... other properties
}
我在基类
上定义了一个过滤器表达式Expression<Func<T1,bool>> filter = p => p.FamilyId == [some value]
这是你要找的吗?该方法有两种类型:第一种允许您将新的输入类型作为参数传入;第二个方法允许您将输入类型作为泛型参数传入,并获得强类型的LambdaExpression。
public static LambdaExpression ChangeInputType<T, TResult>(Expression<Func<T, TResult>> expression, Type newInputType)
{
if (!typeof(T).IsAssignableFrom(newInputType))
throw new Exception(string.Format("{0} is not assignable from {1}.", typeof(T), newInputType));
var beforeParameter = expression.Parameters.Single();
var afterParameter = Expression.Parameter(newInputType, beforeParameter.Name);
var visitor = new SubstitutionExpressionVisitor(beforeParameter, afterParameter);
return Expression.Lambda(visitor.Visit(expression.Body), afterParameter);
}
public static Expression<Func<T2, TResult>> ChangeInputType<T1, T2, TResult>(Expression<Func<T1, TResult>> expression)
{
if (!typeof(T1).IsAssignableFrom(typeof(T2)))
throw new Exception(string.Format("{0} is not assignable from {1}.", typeof(T1), typeof(T2)));
var beforeParameter = expression.Parameters.Single();
var afterParameter = Expression.Parameter(typeof(T2), beforeParameter.Name);
var visitor = new SubstitutionExpressionVisitor(beforeParameter, afterParameter);
return Expression.Lambda<Func<T2, TResult>>(visitor.Visit(expression.Body), afterParameter);
}
public class SubstitutionExpressionVisitor : ExpressionVisitor
{
private Expression before, after;
public SubstitutionExpressionVisitor(Expression before, Expression after)
{
this.before = before;
this.after = after;
}
public override Expression Visit(Expression node)
{
return node == before ? after : base.Visit(node);
}
}
你的要求很不明智。编译器如何知道T1是否可以转换为T2?似乎是在要求可怕的运行时错误,即使可能。*
(*我不认为这是可能的,因为你试图结合反射嵌套的泛型类型)
看起来您想要组合2个表达式- T2
到T1
转换,然后使用给定的结果调用expr
。
这个问题一般讨论两个表达式(Expression