更改LambdaExpression中的参数名称仅用于显示 [英] Changing parameter name in a LambdaExpression just for display

查看:79
本文介绍了更改LambdaExpression中的参数名称仅用于显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个这样的表达式:

Let's say I have an expression like this:

Expression<Predicate<T>> exp

如果我分配以下表达式:

If I assign the following expression:

a => a.First() != 0

然后调用exp.ToString()我将完全获得我传递的表达式,这是非常好的,但是,假设我们想用其他方式更改用于'a'的名称,我们该怎么做? 字符串替换并非在所有情况下都可行(在上面的示例中有效,但是如果参数例如被称为"i",该怎么办?) 是否可以仅在运行时替换参数名称,而不会影响表达式的语义?

and then I call exp.ToString() I will obtain exactly the expression I passed, that is perfectly good, but, suppose we want to change the name we use for 'a' with something else, how can we do ? String replacement would not do in all the case ( it works in the example above,but what if the parameter was called 'i' for example ?) Is it possible to have just the parameter name replacement, run time, without affecting the expression semantic ?

更新 @PhilKlein可以完美运行,但是需要框架4.但是,如果我们需要针对框架3.5,则可以使用 ExpressionVisitor 类rel ="noreferrer">马特·沃伦(Matt Warren),只需将Visit方法从受保护的方法修改为公开的方法即可.

UPDATE The @PhilKlein works perfectly, but requires framework 4. But if we need to target the framework 3.5 we can use an ExpressionVisitor class from Matt Warren, by just modifing from protected to public the Visit method.

推荐答案

它既快速又肮脏,但是如果您使用的是.NET 4.0,则可以创建以下内容:

It's quick and dirty, but assuming you're using .NET 4.0 you could create the following:

public class PredicateRewriter
{
    public static Expression<Predicate<T>> Rewrite<T>(Expression<Predicate<T>> exp, string newParamName)
    {
        var param = Expression.Parameter(exp.Parameters[0].Type, newParamName);
        var newExpression = new PredicateRewriterVisitor(param).Visit(exp);

        return (Expression<Predicate<T>>) newExpression;
    }

    private class PredicateRewriterVisitor : ExpressionVisitor
    {
        private readonly ParameterExpression _parameterExpression;

        public PredicateRewriterVisitor(ParameterExpression parameterExpression)
        {
            _parameterExpression = parameterExpression;
        }

        protected override Expression VisitParameter(ParameterExpression node)
        {
            return _parameterExpression;
        }
    }
}

然后按如下所示使用它:

And then use it as follows:

var newExp = PredicateRewriter.Rewrite(exp, "b");
newExp.ToString(); // returns "b => (b.First() == 0)" in your case

这篇关于更改LambdaExpression中的参数名称仅用于显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆