将Expression <Action <T >>转换为Expression <Func <T >>

时间:2019-09-11 16:02:26

标签: c# expression-trees

我有Expression<Action<T>>,其中Action是函数的调用,但未使用函数结果。让我们考虑以下代码示例:

using System;
using System.Linq.Expressions;

namespace ConsoleApp
{
    class Program
    {
        public class MyArg
        {
            public int Data { get; set; }
        }

        public class MyExecutor
        {
            public bool Executed { get; set; }

            public int MyMethod(int simpleArg, MyArg complexArg)
            {
                int result = simpleArg + complexArg.Data;
                this.Executed = true;
                return result;
            }
        }

        static void Main(string[] args)
        {
            Expression<Action<MyExecutor>> expr = t => t.MyMethod(2, new MyArg { Data = 3 });

            var executor = new MyExecutor();
            Action<MyExecutor> action = expr.Compile();
            action(executor);
            Console.WriteLine(executor.Executed); // true
        }
    }
}

可以有很多不同的动作,带有不同数量的参数。在所有情况下,我只有这样的expr总是调用一个函数,而该函数总是返回相同的类型,在我上面的示例中是int

我需要这样的东西:

static Expression<Func<MyExecutor, int>> ToExpressionOfFunc(Expression<Action<MyExecutor>> expr)
{
    // TODO
    throw new NotImplementedException();
}

能够拨打这样的电话:

    Expression<Func<MyExecutor, int>> funcExpr = ToExpressionOfFunc(expr);
    Func<MyExecutor, int> func = funcExpr.Compile();
    int result = func(executor);
    Console.WriteLine(result); // should print 5

我认为这应该可行,但不知道从何入手。我在调试中看到,有一个expr.Body.Method具有所需的Int32 ReturnType,但不清楚如何正确地将其提取到新的Expression<Func>

1 个答案:

答案 0 :(得分:6)

这很简单,只需使用现有表达式中的正文和参数创建一个新的Expression<Func<MyExecutor, int>>

static Expression<Func<MyExecutor, int>> ToExpressionOfFunc(Expression<Action<MyExecutor>> expr)
{
    return Expression.Lambda<Func<MyExecutor, int>>(expr.Body, expr.Parameters);
}

请注意,如果expr不是返回类型int,则会引发异常。