使用一个lambda EX pression与私有方法方法、lambda、EX、pression

2023-09-03 09:32:59 作者:″痛是痛快的痛

我看了一个答案,包含以下建议code堆栈溢出的问题:

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

Action<Exception> logAndEat = ex => 
{  
    // Log Error and eat it
};

try
{
    // Call to a WebService
}
catch (SoapException ex)
{
    logAndEat(ex);
}
catch (HttpException ex)
{
    logAndEat(ex);
}
catch (WebException ex)
{
    logAndEat(ex);
}

我的问题是:什么是用一个lambda EX pression为LogAndEat相对于(在我看来更简单和更明显)私有方法如下的优势(如果有的话):

My question is: what is the advantage (if any) of using a lambda expression for LogAndEat as opposed to the (in my view simpler and more obvious) private method as follows:

private void LogAndEat(Exception ex)
{
    // Log Error and eat it
}

编辑:谢谢你的答案迄今只是重申我的根本问题一个更清楚一点:哪种方法比较好/你会建议在这种情况下?一个lambda EX pression还是私有方法?

Thanks for the answers so far but just restating my fundamental question a little more clearly: which approach is better/would you recommend in this instance? A lambda expression or a private method?

推荐答案

感谢大家对伟大的答案,我已经向上投,但我想我会总结他们试图捕捉利弊的一个答案。

Thanks everyone for the great answers which I have up-voted, but I thought I'd summarize them to try and capture the pros and cons in one answer.

使用拉姆达EX pression(LE)的优点,而不是一个私有方法:

Pros of using a lambda expression (LE) instead of a private method:

系统LE的作用范围是在其声明,因此如果仅由该方法那么的意图的方法的是由明确由一个lambda EX pression(即使它是可以委托传递出的LE,人们仍然可以说在方法声明LE的目的是使LE的作用域是方法)。也就是说,被明确在其预期的使用方面。 LAMBDA EX pressions行为类似于闭包,以便他们可以访问的变量范围,以他们在声明的方法,也可以说不是通过大量的参数传递给私有方法更简洁。 将一个LE捕获的变量,否则将参数传递给私有方法,这可以被利用来使钻营的一种形式。 A LE is scoped to the method in which it is declared so if it is only used by that method then that intent is made explicit by a lambda expression (even though it is possible to pass out a delegate to the LE, one can still argue the intent of declaring a LE in a method is that the LE is scoped to the method). That is, being explicit in terms of its expected usage. Lambda expressions behave like closures so they can access variables scoped to the method they are declared in. This can be neater than passing lots of parameters to a private method. Variables captured by a LE would otherwise be parameters to a private method and this can be exploited to allow a form of currying.

缺点使用,而不是一个私有方法的lambda EX pression的:

由于LE可以访问变量作用于它们所包含的方法,这是不可能修改code在调用方法,而调试。

还有一个比较主观的可维护性问题,人们可以说,乐都没有得到很好的大多数开发商作为一个私人的方法了解并因此少了几分维护。人们还可以争辩说,LE提高可维护性,因为它被封装在调用它,而不是一个私有方法,这是可见的所有类中的方法。

There is also the more subjective issue of maintainability and one could argue that LE are not as well understood by most developers as a private method and thus are somewhat less maintainable. One could also argue that a LE improves maintainability because it is encapsulated in the method in which it is called as opposed to a private method which is visible to the entire class.