Lambda for Dummies…anyone, anyone? I think not

后端 未结 10 1449
迷失自我
迷失自我 2020-12-22 23:45

In my quest to understand the very odd looking \' => \' operator, I have found a good place to start, and the author is very concise and clear:

         


        
10条回答
  •  -上瘾入骨i
    2020-12-23 00:19

    So, to start off with the scary definition - a lambda is another way of defining an anonymous method. There has (since C# 2.0 I believe) been a way to construct anonymous methods - however that syntax was very... inconvinient.

    So what is an anonymous method? It is a way of defining a method inline, with no name - hence being anonymous. This is useful if you have a method that takes a delegate, as you can pass this lambda expression / anonymous method as a parameter, given that the types match up. Take IEnumerable.Select as an example, it is defined as follows:

    IEnumerable Select(this IEnumerable source, Func selector);
    

    If you were to use this method normally on say a List and select each element twice (that is concatenated to itself):

    string MyConcat(string str){
        return str + str;
    }
    
    ...
    
    void myMethod(){
        IEnumerable result = someIEnumerable.Select(MyConcat);
    }
    

    This is a very inconvinient way of doing this, especially if you wish to perform many of these operations - also typically these kinds of methods you only use once. The definition you showed (parameters => expression) is very consise and hits it spot on. The interesting thing about lambda is that you do not need to express the type of the parameters - as long as they can be infered from the expression. Ie. in Select's case - we know the first parameter must be of type TSource - because the definition of the method states so. Further more - if we call the method just as foo.Select(...) then the return value of the expression will define TResult.

    An interesting thing as well is that for one-statement lambda's the return keyword is not needed - the lambda will return whatever that one expression evaluates to. However if you use a block (wrapped in '{' and '}') then you must include the return keyword like usual.

    If one wishes to, it is still 100% legal to define the types of the parameters. With this new knowledge, let's try and rewrite the previous example:

    void myMethod(){
        IEnumerable result = someIEnumerable.Select(s => s + s);
    }
    

    Or, with explicit parameters stated

    void myMethod(){
        IEnumerable result = someIEnumerable.Select((string s) => s + s);
    }
    

    Another interesting feature of lambda's in C# is their use to construct expression trees. That is probably not "beginner" material though - but in short an expression tree contains all the meta data about a lambda, rather than executable code.

提交回复
热议问题