我有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我有一种感觉,这应该是可能的,但不知道从哪里开始。我在debug中看到有一个expr.Body.Method具有所需的ReturnType为Int32,但不清楚如何将其正确提取到新的Expression<Func>中。
发布于 2019-09-12 00:12:47
这很简单,只需使用现有表达式中的主体和参数创建一个新的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,则会抛出异常。
https://stackoverflow.com/questions/57892949
复制相似问题