有没有比 () => 更好的方式来表达无参数 lambda?
()
看起来很愚蠢。 有没有更好的办法?
例如:
ExternalId.IfNotNullDo(() =>ExternalId =ExternalId.Trim());
The ()
seems silly. is there a better way?
For example:
ExternalId.IfNotNullDo(() => ExternalId = ExternalId.Trim());
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
有点! 城里有一个新的习语,它很好,在某些情况下可能对你有帮助。 这并不完全是你想要的,但有时我想你会喜欢它。
由于下划线 (“_”) 是有效的 C# 标识符,因此在您打算忽略参数的情况下,将其用作 lambda 的参数名称正在成为一种常见的习惯用法。 如果其他编码员知道这个习惯用法,他们会立即知道该参数是不相关的。
例如:
易于打字,传达您的意图,而且也更方便眼睛。
当然,如果您将 lambda 传递给需要表达式树的对象,则这可能不起作用,因为现在您传递的是单参数 lambda,而不是无参数 lambda。
但对于很多情况来说,这是一个很好的解决方案。
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.
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.
For example:
Easy to type, conveys your intent, and easier on the eyes as well.
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,不需要:您需要
() =>
它是用于委托还是表达式? 对于委托,另一个选项是
delegate {...}
。 这可能是理想的,也可能不是理想的,具体取决于具体情况。 当然,它是更多的键......在某些情况下(不是这个)你可以直接使用目标方法 - 即
For a lambda, no: you need
() =>
Is it for a delegate or an expression? For delegates, another option is
delegate {...}
. This may or may not be desirable, depending on the scenario. It is more keys, certainly...In some cases (not this one) you can use a target method directly - i.e.
不,没有。 Lambda 表达式针对单参数情况进行了优化(在语法方面)。
我知道 C# 团队感受到了您的痛苦,并尝试寻找替代方案。 是否会有这样的人是另一回事。
No, there isn't. Lambda expressions are optimised (in terms of syntax) for the single parameter case.
I know that the C# team feels your pain, and have tried to find an alternative. Whether there ever will be one or not is a different matter.
本质上,您正在寻找的是
??
null 合并运算符的逆(在幕后称为Nullable.GetValueOrDefault()
) - 问题是C# 没有提供简洁的 OOTB 答案。不确切知道你在做什么,但正如你正在做的那样:
你可能还会发现一种用途:
这将启用:(
一般来说,我会尝试避免重用/改变变量,因为你似乎是而是按照引入解释变量/拆分临时变量的方向进行操作,即使用新变量而不是
value = value.DefaultOr( _ => _.Trim());
)Essentially what you're looking for is the inverse of the
??
null coalescing operator (which is calledNullable<T>.GetValueOrDefault()
under the covers) - problem is C# doesn't provide a neat OOTB answer.Don't know exactly what you're doing but as you are doing:
you might also find a use for:
which would enable:
(in general, I'd be trying to steer away from reusing / mutating variables as you seem to be doing and instead going in an Introduce Explaining Variable / Split Temporary Variable direction i.e., use a new variable rather than
value = value.DefaultOr( _ => _.Trim());
)