Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
332 views
in Technique[技术] by (71.8m points)

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.

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);

This makes expr become:

() => Invoke(value(Test.Program+<>c__DisplayClass0).func, 5)

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I think what you want to do is use the Target and Method properties of the delegate to pass to create a Call expression. Building on JulianR's sample, this is what it would look like:

Action<int> func = i => Console.WriteLine(i * i);

var callExpr = Expression.Call(Expression.Constant(func.Target), func.Method, Expression.Constant(5));

var lambdaExpr = Expression.Lambda<Action>(callExpr);
var fn = lambdaExpr.Compile();
fn();    //  Prints 25

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...