如何将表达式从类型接口转换为特定类型

在我的界面中,我有以下定义

List GetListOfFoo(Expression<Func> predicate) where T : IFoo; 

在我的实现中,我将以特定类型转换表达式:

 if (typeof(T) == typeof(Foo)) { Expression converted = Expression.Convert(predicate.Body, typeof(Foo)); Expression<Func> newPredicate = Expression.Lambda<Func>(converted, predicate.Parameters); } 

我尝试使用这样的实现:

 Expression<Func> predicate = c => c.Name == "Myname"; _repository.GetListOfFoo(predicate); 

我没有编译错误,但是如果我使用它,我会得到一个exception,即ExpressionBody中定义的bool参数。

我的问题在哪里?

你的代码没有任何意义。

您正在创建一个返回FooExpression.Convert ,然后尝试将其用作返回bool的函数。

Expression.Convert也没有意义; 你不能将bool转换成Foo

你可能想写

 var converted = (Expression>) predicate; 

只要TFoo ,这样就行了。

参数的类型需要更改,而不是表达式的主体。

从您的实现调用后,您将不得不进行转换。

也没理由为什么你需要这个作为Foo : IFoo

我找到了更好的解决方案。 我不需要自己抛出谓词。

 public List GetFoos(Expression> predicate) where T : class, IModel { var result = new List(); var repository = new Repository(); result.AddRange(repository.GetEntities(predicate).ToList().ConvertAll(c => (IFoo)c)); return result; }