Access shared lists with delegate notes

I see some people writing:

//wordList is List<string> 
wordList.ForEach(delegate(string word){ Console.WriteLine(word);});

instead:

foreach(string word in wordList)
{
    Console.WriteLine(word);
}

What is the advantage of this. Also, I could not understand the Action delegate syntax above, although I used delegates in C # 2.0. Basically, I cannot associate the syntax with the concept of delegates that I am familiar with. Could you help me understand the syntax. Is it a reduction?

+3
source share
5 answers

The syntax delegate() {...}is available in .NET 2. It essentially creates a (anonymous) method in the containing class that contains the contents of the delegate. So the syntax above is equivalent

private void actionImpl(string word) {
    Console.WriteLine(word);
}

wordList.ForEach(new Action<string>(actionImpl));

List<T>.ForEach, . , . ,

wordList.ForEach(Console.WriteLine);

Console.WriteLine(string s) Action<string>. ( ) , foreach .

+2

.

, , , : , , . , foreach .

:

, , .. , (, + String.Concat) , . ; "foreach", , , "" , .

+2

- . , . , , , ( ) , .

" ". " ".

" " .

0

Action<string> , .

0

Source: https://habr.com/ru/post/1738724/


All Articles