C# 转换表达式<;行动<;T>&燃气轮机;表达<;Func<;T>&燃气轮机;
我有C# 转换表达式<;行动<;T>&燃气轮机;表达<;Func<;T>&燃气轮机;,c#,expression-trees,C#,Expression Trees,我有表达式,其中动作是函数调用,但函数结果不使用。让我们考虑下面的代码示例: using System; using System.Linq.Expressions; namespace ConsoleApp { class Program { public class MyArg { public int Data { get; set; } } public class MyExecu
表达式
,其中动作是函数调用,但函数结果不使用。让我们考虑下面的代码示例:
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
}
}
}
要想打这样的电话:
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
Expression funcExpr=ToExpressionOfFunc(expr);
Func Func=funcExpr.Compile();
int result=func(执行器);
Console.WriteLine(结果);//应该打印5个
我有一种感觉,这应该是可能的,但不知道从哪里开始。我在debug中看到有一个expr.Body.Method,其返回类型为Int32,但不清楚如何正确地将其提取到新的
表达式中
很简单,只需使用现有表达式的Body和参数创建一个新的表达式
:
static Expression<Func<MyExecutor, int>> ToExpressionOfFunc(Expression<Action<MyExecutor>> expr)
{
return Expression.Lambda<Func<MyExecutor, int>>(expr.Body, expr.Parameters);
}
静态表达式到表达式offunc(表达式expr)
{
返回表达式Lambda(expr.Body,expr.Parameters);
}
请注意,如果
expr
不是返回类型int
步骤1:写入两行代码expr=t=>t.MyMethod(2,new MyArg{Data=3})
和表达式ret_expr=t=>t.MyMethod(2,新的MyArg{Data=3})代码>步骤2:在调试器中查看这两者,以查看表达式树构造中的差异。