Expression Trees and Invoking a Delegate(表达式树和调用委托)
问题描述
所以我有一个 delegate 指向一些我在第一次创建 delegate 对象时实际上并不知道的函数.该对象稍后会设置为某个函数.
So I have a delegate which points to some function which I don't actually know about when I first create the delegate object. The object is set to some function later.
然后我还想创建一个表达式树,它使用参数调用委托(为了这个问题,参数可以是 5).这是我正在努力解决的问题;下面的代码显示了我想要的,但它没有编译.
I also then want to make an expression tree that invokes the delegate with an argument (for this question's sake the argument can be 5). This is the bit I'm struggling with; the code below shows what I want but it doesn't compile.
Func<int, int> func = null;
Expression expr = Expression.Invoke(func, Expression.Constant(5));
对于这个例子我可以做(这很实用,因为我需要在运行时构建表达式树):
For this example I could do (this is practical since I need to build the expression trees at runtime):
Func<int, int> func = null;
Expression<Func<int>> expr = () => func(5);
这使得 expr 变成:
() => Invoke(value(Test.Program+<>c__DisplayClass0).func, 5)
这似乎意味着要使用 delegate func,我需要生成 value(Test.Program+<>c__DisplayClass0).func位.
Which seems to mean that to use the delegate func, I need to produce the value(Test.Program+<>c__DisplayClass0).func bit.
那么,如何创建一个调用委托的表达式树?
So, how can I make an expression tree which invokes a delegate?
推荐答案
好的,这显示了它是如何实现的(但在我看来它很不雅):
OK, this shows how it can be done (but it is very inelegant in my opinion):
Func<int, int> func = null;
Expression<Func<int, int>> bind = (x) => func(x);
Expression expr = Expression.Invoke(bind, Expression.Constant(5));
Expression<Func<int>> lambda = Expression.Lambda<Func<int>>(expr);
Func<int> compiled = lambda.Compile();
Console.WriteLine(expr);
func = x => 3 * x;
Console.WriteLine(compiled());
func = x => 7 * x;
Console.WriteLine(compiled());
Console.Read();
基本上我使用 (x) =>func(x); 来创建一个调用委托所指向的函数.但是您可以看到 expr 过于复杂.出于这个原因,我不认为这个答案很好,但也许可以建立在它的基础上?
Essentially I use (x) => func(x); to make a function that calls what the delegate points to. But you can see that expr is overly complicated. For this reason I don't consider this answer good, but maybe it can be built upon?
这篇关于表达式树和调用委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:表达式树和调用委托
基础教程推荐
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
