c# - 在运行时更改表达式委托(delegate)主体?

标签 c# .net .net-4.0 expression-trees

我有这段代码生成一个将 myNumber 乘以 5 的委托(delegate)

ParameterExpression numParam = Expression.Parameter(typeof(int), "num");
ConstantExpression five = Expression.Constant(5, typeof(int));
BinaryExpression numMultiply = Expression.Multiply(numParam,five);

让我们创建委托(delegate):

Expression<Func<int, int>> lambda1 =
    Expression.Lambda<Func<int, int>>(
        numMultiply,
        new ParameterExpression[] { numParam });
Console.Write(lambda1.Compile()(4));

现在假设我想将此表达式树更改为 Add 而不是 Multiply
这是新行:

BinaryExpression numAdd = Expression.Add(numParam,five);

但是我怎样才能更改 lambda1 以便它现在将使用 numAdd 而不是 multiply

最佳答案

你只需构建一个新的,然后编译它。

Expression<Func<int, int>> lambda1 =
     Expression.Lambda<Func<int, int>>(
         numAdd,
         new ParameterExpression[] { numParam });

来自MSDN page :

Expression trees should be immutable. This means that if you want to modify an expression tree, you must construct a new expression tree by copying the existing one and replacing nodes in it. You can use an expression tree visitor to traverse the existing expression tree.

“应该是”这个短语有点奇怪,但是当您查看 API 时,您会发现所有相关属性(Body、Left、Right)都是只读的。

关于c# - 在运行时更改表达式委托(delegate)主体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14324842/

相关文章:

c# - .net 核心 ProtoBuf 上的序列化程序在哪里?

c# - Asp.net core WEB API 安全的第三方中间件路由?

.net - 提供两个接口(interface)的 Web 服务在 WPF 应用程序中导致错误

c# - 如何使用 ASP.NET MVC 返回动态 CSS?

c# - 无法加载文件或程序集 'Microsoft.Data.Service' 或其依赖项之一。该系统找不到指定的文件

c# - 我是否应该注意到在 .Net 4.0 中使用任务与线程的区别?

c# - Dundas 仪表板图像悬停交互

.net-4.0 - 对于此代码,为什么 PLINQ 比 LINQ 慢?

c# - 标记扩展 'StaticResourceExtension' 需要在 IServiceProvider 中为 ProvideValue 实现 'IXamlSchemaContextProvider'

c# - .CSV 到 SQL CE 表?