gpt4 book ai didi

c# - 将表达式> 转换为表达式>

转载 作者:太空狗 更新时间:2023-10-30 00:47:41 24 4
gpt4 key购买 nike

我有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
}
}
}

可以有很多不同的 Action ,具有不同数量的参数。在所有情况下,我只有这种 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,所需的 ReturnType 为 Int32,但不清楚如何将其正确提取到新的 Expression<Func> .

最佳答案

很简单,新建一个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 .

关于c# - 将表达式<Action<T>> 转换为表达式<Func<T>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57892949/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com