本文介绍了如何手动构建将始终返回true的Expression?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I tried to create Expression, but failed.

我想构建类似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, "_"));
}

这篇关于如何手动构建将始终返回true的Expression?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-03 18:20
查看更多