常见的 C# 习惯用法包括合并?操作员
每个人都至少知道两种常见的 C# 习惯用法,包括合并运算符:
单例运算符
return _staticField = _staticField ?? new SingletonConstructor();
和链运算符:
notNullableResult = nullable1 ?? nullable2 ?? nullable3 ?? default(someType);
它可读、一致、值得使用并且在代码中可识别。
但不幸的是,这就是全部。有时需要扩展或改变。有时,当我看到特定情况时,我会使用它们 - 并且我总是犹豫是否使用它,因为我不知道其他程序员是否真的会轻松阅读它。
你还认识其他人吗?我希望有更具体的用法:例如 Asp.net、EF、LINQ 等任何东西 - 其中合并不仅可以接受,而且非常出色。
Everyone knows at least two common c# idioms including coalesce operator:
a singleton one:
return _staticField = _staticField ?? new SingletonConstructor();
and a chain one:
notNullableResult = nullable1 ?? nullable2 ?? nullable3 ?? default(someType);
it's readable, consistent, worth using and recognizable in code.
But, unfortunately, this is all. Sometimes it will need expanding or change. Sometimes i use them when i see a particular case - and always i hesitate to use it because i dont know if any other programmer will really read it easy.
Do you know any others? I would love to have more specific usages: e.g. Asp.net, EF, LINQ, anything - where coalesce is not only acceptable but remarkable.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对我来说,它转换为 SQL 本身就足够了:
这导致数据库端的
COALSCE
在大多数情况下可以实现非常更干净的 SQL,但实际上并没有任何好的选择。我们正在使用 Oracle,我宁愿不阅读Nvl(Nvl(Nvl(Nvl(
嵌套,谢谢...我将使用我的COALSCE
并运行 我也将它用于这样的属性,我想只是个人口味:
For me, where it translates to SQL is good enough by itself:
This resulting in
COALSCE
on the database side makes for tremendously cleaner SQL in most cases, there just isn't any great alternative. We're using Oracle, I'd rather not read thoughNvl(Nvl(Nvl(Nvl(
nesting thank you...I'll take myCOALSCE
and run with it.I also use it for properties like this, just personal taste I guess:
C# 2.0 中引入空合并运算符的原因是有一种方法可以将默认值分配给 可空类型,从而轻松地将可空类型转换为不可空类型。如果没有
??
,任何转换都需要冗长的if
语句。以下引用摘自 MSDN:您可能会认为以下简化“非常出色”:
而不是
The reason that the null-coalescing operator has been introduced in C# 2.0 was to have an way to assign default values to nullable types and thus easily convert a nullable type into a non-nullable type. Without
??
any conversion would require a lengthyif
statement. The following quote is taken from MSDN:You might consider the following simplification "remarkable":
Instead of