_=> what does this underscore mean in Lambda expressions?

后端 未结 5 512
日久生厌
日久生厌 2020-11-28 07:04

What does an lambda expression like _=> expr mean?

What is the purpose of _ as input to lambda?

Example:

int cou         


        
5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-28 07:25

    I also second the use of _ => _.method() for one-line, method-call lambdas, since it reduces the instruction's cognitive weight. Specially when using generics, writing x => x.method() just adds that split-second consideration of "What's this 'x'? Is it a coordinate in space?".

    Consider the following case:

    Initialize ( _=>_.Init() );

    Used with a Generics call, the underscore in this case works as a "bypass symbol". It avoids redundancy, defining that the type of the argument is obvious and can be infered from usage - just as when you use 'var' to prevent repeating a type declaration. Writing client=>client.Init() here would just make the instruction longer without adding any meaning to it.

    Obviously, this doesn't apply to the parameters to be passed to the method, which should be named descriptively. Eg.: Do( id=>Log(id) );

    The single-underscore-parameter usage for method calls is hardly justifiable when using a block of code instead of a one-liner, since the lambda identifier gets disconnected from its generics definition. In general when the same identifier is to be reused, give it a descriptive name.

    The bottom line is that verbosity is only justifiable for disambiguation, especially for lambdas, which were created to simplify anonymous delegates creation in the first place. In any case, common sense should be used, balancing out legibility and conciseness. If the symbol is only a "hook" to the real functionality, one character identifiers are perfectly fine. That's the case with For-loops and the "i" and "j" letters as indexers.

提交回复
热议问题