使用 .NET 3.5 调用多个表达式

Invoke multiple Expressions with .NET 3.5

备选方案

虽然我(并且对于这个项目仍然是)仅限于 .NET 3.5,但我已经成功地使用了表达式树的 DLR 版本。这是根据 Apache 许可版本 2.0 发布的。

这增加了对所有(可能或多或少,但可能不是).NET 4.0+ 表达式的支持,例如 BlockExpression 我需要这个问题。

The source code can be found on GitHub.


原问题

在我当前的项目中,我正在编译一个具有可变数量参数的表达式树。我有一个 Expressions 链需要调用。在 .NET 4.0+ 中,我只使用 Expression.Block 来实现这一点,但是,我仅限于在该项目中使用 .NET 3.5。

现在我发现了解决此问题的大量 hack,但我认为这不是解决此问题的最佳方法。

代码:

using System;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;

class Program
{
    struct Complex
    {
        public float Real;
        public float Imaginary;
    }

    // Passed to all processing functions
    class ProcessContext
    {
        public ConsoleColor CurrentColor;
    }

    // Process functions. Write to console as example.
    static void processString(ProcessContext ctx, string s)
    { Console.ForegroundColor = ctx.CurrentColor; Console.WriteLine("String: " + s); }
    static void processAltString(ProcessContext ctx, string s)
    { Console.ForegroundColor = ctx.CurrentColor; Console.WriteLine("AltString: " + s); }
    static void processInt(ProcessContext ctx, int i)
    { Console.ForegroundColor = ctx.CurrentColor; Console.WriteLine("Int32: " + i); }
    static void processComplex(ProcessContext ctx, Complex c)
    { Console.ForegroundColor = ctx.CurrentColor; Console.WriteLine("Complex: " + c.Real + " + " + c.Imaginary + "i"); }

    // Using delegates to access MethodInfo, just to simplify example.
    static readonly MethodInfo _processString = new Action<ProcessContext, string>(processString).Method;
    static readonly MethodInfo _processAltString = new Action<ProcessContext, string>(processAltString).Method;
    static readonly MethodInfo _processInt = new Action<ProcessContext, int>(processInt).Method;
    static readonly MethodInfo _processComplex = new Action<ProcessContext, Complex>(processComplex).Method;

    static void Main(string[] args)
    {
        var methodNet40 = genNet40();
        var methodNet35 = genNet35();

        var ctx = new ProcessContext();
        ctx.CurrentColor = ConsoleColor.Red;

        methodNet40(ctx, "string1", "string2", 101, new Complex { Real = 5f, Imaginary = 10f });
        methodNet35(ctx, "string1", "string2", 101, new Complex { Real = 5f, Imaginary = 10f });


        // Both work and print in red:

        // String: string1
        // AltString: string2
        // Int32: 101
        // Complex: 5 + 10i
    }

    static void commonSetup(out ParameterExpression pCtx, out ParameterExpression[] parameters, out Expression[] processMethods)
    {
        pCtx = Expression.Parameter(typeof(ProcessContext), "pCtx");

        // Hard-coded for simplicity. In the actual code these are reflected.
        parameters = new ParameterExpression[]
        {
            // Two strings, just to indicate that the process method
            // can be different between the same types.
            Expression.Parameter(typeof(string), "pString"),
            Expression.Parameter(typeof(string), "pAltString"),
            Expression.Parameter(typeof(int), "pInt32"),
            Expression.Parameter(typeof(Complex), "pComplex")
        };

        // Again hard-coded. In the actual code these are also reflected.
        processMethods = new Expression[]
        {
            Expression.Call(_processString, pCtx, parameters[0]),
            Expression.Call(_processAltString, pCtx, parameters[1]),
            Expression.Call(_processInt, pCtx, parameters[2]),
            Expression.Call(_processComplex, pCtx, parameters[3]),
        };
    }

    static Action<ProcessContext, string, string, int, Complex> genNet40()
    {
        ParameterExpression pCtx;
        ParameterExpression[] parameters;
        Expression[] processMethods;
        commonSetup(out pCtx, out parameters, out processMethods);

        // What I'd do in .NET 4.0+
        var lambdaParams = new ParameterExpression[parameters.Length + 1]; // Add ctx
        lambdaParams[0] = pCtx;
        Array.Copy(parameters, 0, lambdaParams, 1, parameters.Length);

        var method = Expression.Lambda<Action<ProcessContext, string, string, int, Complex>>(
            Expression.Block(processMethods),
            lambdaParams).Compile();

        return method;
    }

    static Action<ProcessContext, string, string, int, Complex> genNet35()
    {
        ParameterExpression pCtx;
        ParameterExpression[] parameters;
        Expression[] processMethods;
        commonSetup(out pCtx, out parameters, out processMethods);

        // Due to the lack of the Block expression, the only way I found to execute
        // a method and pass the Expressions as its parameters. The problem however is
        // that the processing methods return void, it can therefore not be passed as
        // a parameter to an object.

        // The only functional way I found, by generating a method for each call,
        // then passing that as an argument to a generic Action<T> invoker with
        // parameter T that returns null. A super dirty probably inefficient hack.

        // Get reference to the invoke helper
        MethodInfo invokeHelper =
            typeof(Program).GetMethods(BindingFlags.Static | BindingFlags.NonPublic)
            .Single(x => x.Name == "invokeHelper" && x.IsGenericMethodDefinition);

        // Route each processMethod through invokeHelper<T>
        for (int i = 0; i < processMethods.Length; i++)
        {
            // Get some references
            ParameterExpression param = parameters[i];
            Expression process = processMethods[i];

            // Compile the old process to Action<T>
            Type delegateType = typeof(Action<,>).MakeGenericType(pCtx.Type, param.Type);
            Delegate compiledProcess = Expression.Lambda(delegateType, process, pCtx, param).Compile();

            // Create a new expression that routes the Action<T> through invokeHelper<T>
            processMethods[i] = Expression.Call(
                invokeHelper.MakeGenericMethod(param.Type),
                Expression.Constant(compiledProcess, delegateType),
                pCtx, param);
        }

        // Now processMethods execute and then return null, so we can use it as parameter
        // for any function. Get the MethodInfo through a delegate.
        MethodInfo call2Helper = new Func<object, object, object>(Program.call2Helper).Method;

        // Start with the last call
        Expression lambdaBody = Expression.Call(call2Helper,
            processMethods[processMethods.Length - 1],
            Expression.Constant(null, typeof(object)));

        // Then add all the previous calls
        for (int i = processMethods.Length - 2; i >= 0; i--)
        {
            lambdaBody = Expression.Call(call2Helper,
                processMethods[i],
                lambdaBody);
        }

        var lambdaParams = new ParameterExpression[parameters.Length + 1]; // Add ctx
        lambdaParams[0] = pCtx;
        Array.Copy(parameters, 0, lambdaParams, 1, parameters.Length);

        var method = Expression.Lambda<Action<ProcessContext, string, string, int, Complex>>(
            lambdaBody,
            lambdaParams).Compile();

        return method;
    }

    static object invokeHelper<T>(Action<ProcessContext, T> method, ProcessContext ctx, T parameter)
    {
        method(ctx, parameter);
        return null;
    }

    static object call2Helper(object p1, object p2) { return null; }
}

我想找到一个好的替代方案的主要原因是不必将这个丑陋的 hack 放入我们的代码库中(尽管如果没有合适的替代方案我会这样做)。

另一方面,它也很浪费,而且它在可能较弱的客户端机器上运行,在视频游戏中每秒可能运行几千次。现在它不会破坏或影响我们游戏的性能,但它不可忽视。每种方法的函数调用量。

测试性能(在发布版本中)在调用过程中产生了 3.6 倍的差异。在调试版本中,速度差异大约是 6 倍,但这并不重要,我们开发人员拥有更强大的机器。

我认为没有理由为您要调用的每个操作编译一个 lambda。使处理函数 return 不同于 void。然后就可以生成:

static object Dummy(object o1, object o2, object o3, ...) { return null; }

Dummy(func1(), func2(), func3());

Dummy 应该被内联。

即使您必须编译多个 lambda,您也不需要在运行时接受委托调用。您可以访问 Delegate.Method 已编译的 lambda 并直接发出对该方法的静态调用。

即使您保持相同(或相似)的基本策略但稍微重构代码,您也可以简化代码。

编写您自己的 Block 实现,它接收一系列表达式并创建一个表示调用所有表达式的表达式。

为此,您将拥有一个私有实现方法,该方法采用多个操作并调用所有这些操作,您将把所有的表达式转换为传递给该方法的操作,然后您可以 return 表示该方法调用的表达式:

//TODO come up with a better name
public class Foo
{
    private static void InvokeAll(Action[] actions)
    {
        foreach (var action in actions)
            action();
    }
    public static Expression Block(IEnumerable<Expression> expressions)
    {
        var invokeMethod = typeof(Foo).GetMethod("InvokeAll",
            BindingFlags.Static | BindingFlags.NonPublic);
        var actions = expressions.Select(e => Expression.Lambda<Action>(e))
            .ToArray();
        var arrayOfActions = Expression.NewArrayInit(typeof(Action), actions);
        return Expression.Call(invokeMethod, arrayOfActions);
    }
}

这不涉及提前编译任何表达式,但更重要的是它允许您将创建表达式块的逻辑从您的用法中分离出来,让您可以轻松地将其基于in/out关于您使用的框架版本。