views:

46

answers:

2

I have a method that expects an Action<string>

I call the method as follows:

commandProcessor.ProcessCommand(s=> ShowReceipt("MyStringValue"))


ProccessCommand(Action<string> action)
{
  action.Invoke(...); // How do I get the reffered string?
}

Do I have to use Expression<Action<string>> ? If so, how do I get the parameter values?

+2  A: 

You would indeed have to use Expression<Action<string>>... and even then you'd have to make some assumptions or write quite a lot of code to make it very robust.

This post may help you - it's pretty similar - but I would try to think of an alternative design if possible. Expression trees are great, and very interesting... but I typically think of them as a bit of a last resort.

Jon Skeet
+1  A: 

Usually you would call it like this:

 commandProcessor.ProcessCommand(s=> ShowReceipt(s)) 

or simply

 commandProcessor.ProcessCommand(ShowReceipt)

and supply the string to the action in the called method:

 ProcessCommand(Action<string> action) 
 { 
  action("MyStringValue"); 
 } 
Henrik
my string value is different. What I now do is to have an extra parameter string. ProcessCommand(Action<string> action, string str)
Rookian