表达式树和调用代理 [英] Expression Trees and Invoking a Delegate

查看:97
本文介绍了表达式树和调用代理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个 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)

表示要使用委托 func ,我需要产生 value(Test。程序+<> 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?

这篇关于表达式树和调用代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆