c# - 如何手动构建将始终返回 true 的表达式?

标签 c# linq lambda expression-trees

我尝试创建表达式,但失败了。

我想构建类似 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/

相关文章:

C# KeyEventArgs 有错误的 KeyCode 和 KeyData 值

c# - 为手动生成的 WCF(客户端)代理实现异步/等待模式

c# - 从 MemberExpression 和 Constant 创建 Func<T, bool>

java - 接受并返回相同类型的通用函数接口(interface)

c++ - 使用元组在 lambda 上推导模板参数失败

c# - 在 vs2010 中开发 iphone\android 应用程序需要做什么?

c# - 寻找一个非常简单的缓存示例

linq - 类似于 LINQ 的 DefaultIfEmpty 和 FirstOrDefault 的 Groovy 方法

c# - 从 C# KeyValuePair 中选择值

asp.net - 可以在 linq 查询中将数据类型分配给匿名类型的成员吗?