开发者

Use of anonymous method

开发者 https://www.devze.com 2023-03-07 03:42 出处:网络
I haven\'t used anonymous methods. I found a code where a list is being iterated as shown in code snippet 1. Why would the code snippet 1 be preferred over 2?

I haven't used anonymous methods. I found a code where a list is being iterated as shown in code snippet 1. Why would the code snippet 1 be preferred over 2?

    List<String> names = new List<String>(); 

    ... 
    //Code snippet 1
    names.ForE开发者_C百科ach(delegate(String name)
    {
        Console.WriteLine(name);
    });

    //Code snippet 2
    foreach (string name in names)
    {
        Console.WriteLine(name);
    }


I don't see snippet 1 used much at all. I do see a variation of it using lambda expressions.

names.ForEach(x=> Console.WriteLine(x));


In this case, there is no benefit.

You would find older programmers using method 2 in your example and newer programmers might use method 1.

Older programmers have more experience prior to anonymous methods, anonymous methods are new and not "ingrained in their soul" and they automatically program in style #2.

New programmers might use #1 because they keep thinking everything is a method call.

0

精彩评论

暂无评论...
验证码 换一张
取 消