【发布时间】:2016-04-21 14:51:17
【问题描述】:
我尝试创建 Expression,但失败了。
我想构建类似Expression<Func<typeof(type), bool>> expression = _ => true;的东西
我的尝试:
private static Expression GetTrueExpression(Type type)
{
LabelTarget returnTarget = Expression.Label(typeof(bool));
ParameterExpression parameter = Expression.Parameter(type, "x");
var resultExpression =
Expression.Return(returnTarget, Expression.Constant(true), typeof(bool));
var delegateType = typeof(Func<,>).MakeGenericType(type, typeof(bool));
return Expression.Lambda(delegateType, resultExpression, parameter); ;
}
用法:
var predicate = Expression.Lambda(GetTrueExpression(typeof(bool))).Compile();
但我收到错误消息:Cannot jump to undefined label ''
【问题讨论】:
-
您可以尝试使用阿尔巴哈里兄弟的
PredicateBuilder。var expr = PredicateBuilder.True<T>();albahari.com/nutshell/predicatebuilder.aspx -
typeof(type)在你的表达式中将总是返回Type -
这也可以:
public static Expression GetTrueExpression<T>() => Expression<Func<T, bool>>)(x => true); var predicate = GetTrueExpression<Object>();
标签: c# linq lambda expression-trees