ActionltActionltstringintgtgt and Lambda Expression in C

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

I ve searched on this, but don t really know how to word the question to get the answer so far I can t find anything on nested actions like this with Lambda expressions. I can find lots of help on passing lambda expressions as parameters where the parameter is a delegate and in fact I m doing that lots in my code. It s the nested lambda expression that s giving me problems.

I have a class with a property of type

Action<Action<string,int>> myAction

and I want to assign it with a Lambda expression. I can do it without Lambda expressions using real methods that I have elsewhere in the code. I can also do something simple like

myAction = ((a) => { a("a string", 0); });

but I would like to asign the sub-action and the action in one Lambda. Something like...

myAction = (((s,i)=>{//sub-action body here})=> { //do something here});

But this syntax doesn t work. Is there a way to do this, or do I have to define my methods in advance and do it without a Lambda expression if I want to do this?

Answers

        Action<Action<string, int>> myAction = a => (new Action<string, int>((s, i) => Console.WriteLine(i + s)))("hello", 1);
        myAction(null);  //1hello
        Console.ReadLine();

though its equal to

        Action<Action<string, int>> myAction = a => Console.Writeline("1hello");

you just ignore an argument

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/36474153/actionactionstring-int-and-lambda-expression-in-c-sharp

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils