c# - Transform a delegate to a Expression Tree -


I wonder if you can make and modify the expression tree outside an existing representative.

Like

  Public Zero Foo () {Console.WriteLine (1000); } .... Expression exp = Foo.GetExpression (); // Now do something that changes from 1000 to 2000 ...  

So I would like to reverse engineer a universal stimulus system.

My problem is that I have such a construction:

  var work = new action [20]; (I.e. = 20; i ++) works for [i] = () = & gt; {Console.light line (i); };  

And the way C # works all the same (print 20). But I want

  to work [5] ()  

print 5

  works [ 11] ()  

print 11 and so on.

So I need to calculate 20 different representatives and I wonder what is a "good" approach to do this. Of course I could just write:

  works [0] = () => Console.WriteLine (0); Works [1] = () = & gt; Console.WriteLine (1); Works [2] = () = & gt; Console.WriteLine (2); Works [3] = () = & gt; Console.WriteLine (3); ....  

But this is not a good way in my eyes ...

Anton's solution is almost correct, but he is copying the variable at the wrong time. You want it:

 for  (int i = 0; i! = 20; i ++) {int tmp = i; Works [i] = () = & gt; Console.WriteLine (tmp); }  

tmp > instead of i - - and only one of the captured variables << em> The I variable, which varies on every move, lets you get the "new" tmp variable for each walk.

See Eric Lipert's blog post on the subject (,) for more details.

(To answer the basic question according to the title - You can not make an expression tree from a representative here in a useful way - the only expression tree you can create is the one which only Calling the original representative.)


Comments

Popular posts from this blog

php - multilevel menu with multilevel array -

c# - TypeConverter in propertygrid only converts from string, not to -

jQuery UI: Datepicker month format -