How to manually build Expression which will return always true?

爷,独闯天下 提交于 2019-12-12 10:47:47

问题


I tried to create Expression, but failed.

I want to build something like Expression<Func<typeof(type), bool>> expression = _ => true;

My attempt:

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); ;
}

Usage:

var predicate = Expression.Lambda(GetTrueExpression(typeof(bool))).Compile();

But I am getting the error: Cannot jump to undefined label ''


回答1:


As simple as that:

private static Expression GetTrueExpression(Type type)
{
    return Expression.Lambda(Expression.Constant(true), Expression.Parameter(type, "_"));
}



回答2:


There is a nice tool which can help you construct expression trees http://tryroslyn.azurewebsites.net/ .

I've added a linq to @Ivan`s example of GetTrueExpression



来源:https://stackoverflow.com/questions/36773215/how-to-manually-build-expression-which-will-return-always-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!