Rookian
Rookian

Reputation: 20559

How to get the referred string of an Action<string> delegate?

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?

Upvotes: 0

Views: 244

Answers (2)

Henrik
Henrik

Reputation: 23324

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

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503120

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.

Upvotes: 2

Related Questions