问题描述
所以我有一个 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?
这篇关于表达式树和调用委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!