如何格式化 lambda 表达式和匿名方法以获得最大的可读性?
例如:
Sorter.SortBy ( array, ( a, b ) =>
{
return a > b;
} );
为了获得最大的可读性,格式化它们的最佳方式是什么?
还要考虑一个参数 lambda 版本以及其他可能常用的情况。
指导方针是什么?
For instance:
Sorter.SortBy ( array, ( a, b ) =>
{
return a > b;
} );
What's the best way to format them for maximum readibility?
Also think of it for one parameter lambda version, and other cases that might be used commonly.
What are the guidelines?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
当处理复杂的 lambda 表达式时(在我看来,不仅仅是一行),我实际上更喜欢回归到老式的 2.0 匿名方法:
DoSomething(
委托(int a, int b)
{
int c = a + b;
int d = /* 等等等等 */
返回d;
});
当 lambda 包含不止一行时,我喜欢查看参数的类型,而不仅仅是 (a, b)。 但这只是我。
When dealing with complex lambdas (more than just one line, in my opinion), I actually prefer to regress to the old-fashioned 2.0 anonymous methods:
DoSomething(
delegate (int a, int b)
{
int c = a + b;
int d = /* blah blah */
return d;
});
When the lambda contains more than just one line, I like to see the types of the parameters instead of just (a, b). But that's just me.
为什么在你的例子中使用大括号? 您不认为这更具可读性吗? :
编辑(回应评论):
如果您的 lambda 需要临时变量或其他无法在单个表达式中表达的东西,您应该使用大括号和明确的返回语句。 在所有(好吧,大多数)其他情况下,省略它们会更干净,因为它看起来更直观(无论如何对我来说)。
Why the curly brackets in your example? Don't you think this is more readable? :
EDIT (in response to comments):
If your lambda requires temporary variables or other stuff that can't be expressed in a single expression, you should use the curly brackets and an explicit return statement. In all (well, most) other cases it's cleaner to omit them, because it looks more intuitive (to me anyway).
您将很难决定哪种格式化策略最好,因为这通常是非常主观的。
您可以看看 ReSharper 是如何做到的,因为它允许您稍微自定义格式。
You're going to have trouble deciding what formatting strategy is best since this is usually very subjective.
You could have a look at how ReSharper does it, since it allows you to customize the formatting a bit.