C#防爆pression树木和调用一个委托 [英] C# Expression Trees and Invoking a 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.
我也那么想打一个前pression树调用委托有一个参数(对于这个问题的缘故参数可以是 5
)。这是位我挣扎;在code以下显示了我想要的,但它并没有编译。
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));
在这个例子中,我可以做的(这是可行的,因为我需要建立前pression树木在运行时):
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)
这似乎意味着,使用代理
FUNC
,我需要制作的值(Test.Program +&LT;&GT; 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.
那么,如何才能让一个前pression树,调用一个代表?
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)=&GT; 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?
这篇关于C#防爆pression树木和调用一个委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!