我尝试创建表达式,但失败了。
我想构建类似 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 ''
最佳答案
就这么简单:
private static Expression GetTrueExpression(Type type)
{
return Expression.Lambda(Expression.Constant(true), Expression.Parameter(type, "_"));
}
关于c# - 如何手动构建将始终返回 true 的表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36773215/