繁体   English   中英

重写表达式以使用自定义方法替换List.Contains

[英]Rewrite expression to replace List.Contains with custom method

为了扩大我的技能,我正在努力学习如何重写表达式。

目标:给定一个表达式,我想通过调用我自己的静态方法InList来替换List.Contains()实例。 例如,以下两个表达式应该是等效的:

Expression<Func<Foo,bool>> expr1 = myRewriter.Rewrite(foo => fooList.Contains(foo));
Expression<Func<Foo,bool>> expr2 = foo => InList(foo, fooList);

我的尝试:我已经了解到使用自定义ExpressionVisitor是基于现有表达式创建新表达式的最佳方法。 但是,我无法构建一个实际调用我的方法的新MethodCallExpression 这是我尝试过的:

public class InListRewriter<T> : ExpressionVisitor
{
    public static bool InList(T target, List<T> source)
    {
        // this is my target method
        return true;
    }

    public Expression<Func<T, bool>> Rewrite(Expression<Func<T, bool>> expression)
    {
        return Visit(expression) as Expression<Func<T,bool>>;
    }

    protected override Expression VisitMethodCall(MethodCallExpression node)
    {
        // Only rewrite List.Contains()
        if (!node.Method.Name.Equals("Contains", StringComparison.InvariantCultureIgnoreCase))
            return base.VisitMethodCall(node);

        // Extract parameters from original expression
        var sourceList = node.Object;                   // The list being searched
        var target = node.Method.GetParameters()[0];    // The thing being searched for

        // Create new expression
        var type = typeof (InListRewriter<T>);
        var methodName = "InList";
        var typeArguments = new Type[] { };
        var arguments = new[] { Expression.Parameter(target.ParameterType, target.Name), sourceList };
        var newExpression = Expression.Call(type, methodName, typeArguments, arguments);

        return newExpression;
    }
}

但是,当我通过new InListRewriter<Foo>().Rewrite(foo => fooList.Contains(foo)) InvalidOperationException时,我在Expression.Call期间得到一个InvalidOperationException

类型'MyNamespace.InListRewriter`1 [MyNamespace.Foo]'上的方法'InList'与提供的参数兼容。

我甚至尝试使用非常通用的签名创建一个新的InList:

public static bool InList(params object[] things) {...}

但仍然收到同样的错误。 我究竟做错了什么? 我甚至想做什么?

您的代码有一个大问题:它传递的参数不正确,特别是第一个。

而不是Expression.Parameter(target.ParameterType, target.Name)您需要使用实际参数: node.Arguments[0]

此外,我建议你使用Expression.Call的不同重载:带有MethodInfo的重载。

最终的代码看起来像这样:

protected override Expression VisitMethodCall(MethodCallExpression node)
{
    // Only rewrite List.Contains()
    if (!node.Method.Name.Equals("Contains",
                                 StringComparison.InvariantCultureIgnoreCase))
        return base.VisitMethodCall(node);

    // Extract parameters from original expression
    var sourceList = node.Object;      // The list being searched
    var target = node.Arguments[0];    // The thing being searched for
    var newMethod = GetType().GetMethod("InList",
                                        BindingFlags.Static | BindingFlags.Public);

    // Create new expression
    var newExpression = Expression.Call(newMethod, target, sourceList);

    return newExpression;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM