匿名方法/Lambda(编码标准) [英] Anonymous Methods / Lambda's (Coding Standards)

查看:73
本文介绍了匿名方法/Lambda(编码标准)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在杰弗里·里希特(Jeffrey Richter)的通过C#进行CLR"(.net 2.0版,第353页)中,他说,作为一个自律,他制作匿名函数的长度绝不超过3行代码.他主要引用可读性/可理解性作为其原因.这很适合我,因为我已经习惯于使用不超过5行的匿名方法.

In Jeffrey Richter's "CLR via C#" (the .net 2.0 edtion page, 353) he says that as a self-discipline, he never makes anonymous functions longer than 3 lines of code in length. He cites mostly readability / understandability as his reasons. This suites me fine, because I already had a self-discipline of using no more than 5 lines for an anonymous method.

但是,该编码标准"建议如何与lambda的建议堆叠在一起?从表面上看,我会一视同仁-保持lambda一样短.但是其他人对此有何看法?特别地,当在(可以说)它们最亮的地方使用lambda时-在LINQ语句中使用时-是否有真正的理由放弃该自律/编码标准?

But how does that "coding standard" advice stack against lambda's? At face value, I'd treat them the same - keeping a lambda equally as short. But how do others feel about this? In particular, when lambda's are being used where (arguably) they shine brightest - when used in LINQ statements - is there genuine cause to abandon that self-discipline / coding standard?

推荐答案

请记住,自2.0版以来情况发生了很大变化.例如,考虑.NET 4的Parallel Extensions,它大量使用委托.您可能有:

Bear in mind that things have changed a lot since 2.0. For example, consider .NET 4's Parallel Extensions, which use delegates heavily. You might have:

Parallel.For(0, 100, i => 
{
    // Potentially significant amounts of code
});

对我来说,这是lambda表达式还是匿名方法都没有关系-实际使用的方式与.NET 2.0中的委托通常不同.

To me it doesn't matter whether this is a lambda expression or an anonymous method - it's not really being used in the same way that delegates typically were in .NET 2.0.

在正常的LINQ范围内,我通常不会发现自己使用大型lambda表达式-当然不是根据语句的数量.有时,一个特定的表达式就 lines 而言可能会很长,因为它投射了许多属性.替代方案是排长队!

Within normal LINQ, I don't typically find myself using large lambda expressions - certainly not in terms of the number of statements. Sometimes a particular single expression will be quite long in terms of lines because it's projecting a number of properties; the alternative is having huge lines!

实际上,LINQ倾向于使用单表达式lambda表达式(甚至没有花括号).看到LINQ的用法时,我感到非常惊讶,它有一个lambda表达式,其中包含5条语句.

In fact, LINQ tends to favour single-expression lambda expressions (which don't even have braces). I'd be fairly surprised to see a good use of LINQ which had a lambda expression with 5 statements in.

这篇关于匿名方法/Lambda(编码标准)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆