C#中表达式树的ByRef参数

Man*_*nia 7 c# expression-trees

如果我想创建一个使用out参数调用方法的表达式树,然后返回该out值作为结果..我将如何处理它?

以下不起作用(抛出运行时异常),但也许最能说明我正在尝试做的事情:

private delegate void MyDelegate(out int value);
private static Func<int> Wrap(MyDelegate dele)
{
    MethodInfo fn = dele.Method;
    ParameterExpression result = ParameterExpression.Variable(typeof(int));
    BlockExpression block = BlockExpression.Block(
        typeof(int), // block result
        Expression.Call(fn, result), // hopefully result is coerced to a reference
        result); // return the variable
    return Expression.Lambda<Func<int>>(block).Compile();
}

private static void TestFunction(out int value)
{
    value = 1;
}

private static void Test()
{
    Debug.Assert(Wrap(TestFunction)() == 1);
}
Run Code Online (Sandbox Code Playgroud)

我知道这可以在原始IL(或者根本没有运行时编译)中相当容易地解决,但不幸的是,这是一个更大的表达式构建过程的一部分...所以我真的希望这不是一个限制,因为完全重写将不仅仅是一种痛苦.

max*_*max 7

这对我有用:

    private static Func<int> Wrap(MyDelegate dele)
    {
        var fn = dele.Method;
        var result = ParameterExpression.Variable(typeof(int));
        var block = BlockExpression.Block(
            typeof(int),
            new[] { result },
            new Expression[]
            {
                Expression.Call(fn, result),
                result,
            });
        return Expression.Lambda<Func<int>>(block).Compile();
    }
Run Code Online (Sandbox Code Playgroud)