Using a lambda expression versus a private method

前端 未结 7 1231
北海茫月
北海茫月 2021-02-02 13:42

I read an answer to a question on Stack Overflow that contained the following suggested code:

Action logAndEat = ex => 
{  
    // Log Error          


        
7条回答
  •  刺人心
    刺人心 (楼主)
    2021-02-02 14:19

    A lot comes down to personal preference, nobody can say one absolute way is the right way or the wrong way.

    Lambda Expressions behave like closures in other languages, the cool thing about them is that they can access variables scoped to the method they're declared in. This adds a lot of flexibility to what you can do in your code, but comes at a cost of not being able to modify code in that method while debugging.

    For that reason, if you're going to be logging errors, you might find yourself in a debugger in that method at some time or another. If you use a lambda, you won't be able to modify any code at runtime - so for this reason my preference would be to use a separate private method that accepts the exception as its parameter.

提交回复
热议问题