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

sar*_*arh 4 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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

我需要这样的东西:

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

才能拨打这样的电话:

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

我感觉这应该可行,但是不知道从哪里开始。我在调试中看到,有一个expr.Body.Method具有所需的Int32 ReturnType,但不清楚如何正确地将其提取到new Expression<Func>

Ren*_*ogt 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);
}
Run Code Online (Sandbox Code Playgroud)

请注意,如果expr不是return type,则会引发异常int