有没有比 () => 更好的方法来表达无参数的 lambda? [英] Is there a better way to express a parameterless lambda than () =>?

查看:27
本文介绍了有没有比 () => 更好的方法来表达无参数的 lambda?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

() 看起来很傻.有没有更好的办法?

The () seems silly. is there a better way?

例如:

ExternalId.IfNotNullDo(() => ExternalId = ExternalId.Trim());

推荐答案

有点!镇上有一个新的成语,它很好,在某些情况下可能对您有所帮助.它并不完全是您想要的,但有时我认为您会喜欢它.

Sort of! There is a new idiom in town, that is nice and may help you in some cases. It is not fully what you want, but sometimes I think you will like it.

由于下划线 ("_") 是有效的 C# 标识符,因此在您计划忽略参数的情况下,将其用作 lambda 的参数名称正成为一种常见的习惯用法.如果其他编码人员知道这个习语,他们会立即知道该参数无关紧要.

Since underscore ("_") is a valid C# identifier, it is becoming a common idiom to use it as a parameter name to a lambda in cases where you plan to ignore the parameter anyway. If other coders are aware of the idiom, they will know immediately that the parameter is irrelevant.

例如:

ExternalId.IfNotNullDo( _ => ExternalId=ExternalId.Trim());

易于打字,传达您的意图,也更容易打字.

Easy to type, conveys your intent, and easier on the eyes as well.

当然,如果您将 lambda 传递给需要表达式树的对象,这可能不起作用,因为现在您传递的是单参数 lambda 而不是无参数 lambda.

Of course, if you're passing your lambda to something that expects an expression tree, this may not work, because now you're passing a one-parameter lambda instead of a no-parameter lambda.

但在很多情况下,这是一个不错的解决方案.

But for many cases, it is a nice solution.

这篇关于有没有比 () => 更好的方法来表达无参数的 lambda?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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