为什么 C# 中没有 ||= 或 &&= 运算符?
我们为所有逻辑运算符、移位运算符、加法运算符和所有乘法运算符提供了等效的赋值运算符。
为什么逻辑运算符被遗漏了? 是否有一个很好的技术原因来解释为什么它很难?
We have equivalent assignment operators for all Logical operators, Shift operators, Additive operators and all Multiplicative operators.
Why did the logical operators get left out?
Is there a good technical reason why it is hard?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
他们没有。如果需要,您可以执行
&=
或|=
或^=
。||
和&&
运算符没有复合形式,因为坦率地说,它们有点愚蠢。在什么情况下,如果左侧没有改变,则右侧不会被评估?似乎只有少数人会真正使用这个功能,那么为什么要添加它呢?
有关复合运算符的更多信息,请参阅我的严肃文章:
https://learn.microsoft.com/en -us/archive/blogs/ericlippert/compound-assignment-part-one
以及后续的愚人节文章:
https://learn.microsoft.com/en -us/archive/blogs/ericlippert/compound-taskment-part-two
They didn't. You can do
&=
or|=
or^=
if you want.The
||
and&&
operators do not have a compound form because frankly, they're a bit silly. Under what circumstances would you want to saysuch that the right hand side is not evaluated if the left hand side does not change? It seems like only a few people would actually use this feature, so why put it in?
For more information about the compound operators, see my serious article here:
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/compound-assignment-part-one
and the follow-up April-Fools article here:
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/compound-assignment-part-two
也许只是使用
我猜这部分是因为
a ||= b
有点令人困惑,因为可能有两个版本的实现:a = a || b
,或a = b ||一个。它们的行为不同,因为有时不计算表达式的右侧。
maybe just use
I guess it is partially because
a ||= b
is kind of confusing because there might be two versions of the implementation:a = a || b
, ora = b || a
. And they act differently because the right-hand side of the expression is sometimes not evaluated.在C#中存在双问号运算符(空合并运算符)。
它有两种形式:
?
第一种形式的计算结果为: a = b != null 乙:丙;
第二个 - 就是您要问的: a = a != null ?甲:乙;
当然,这些变量中的任何一个都可能是复杂的表达式。
这是一个参考: null-coalescing运算符
In the C# there is a double question mark operators (null-coalescing operators).
There are two forms of it:
and
The first one evaluates as: a = b != null ? b : c;
The second one - is what you are asking: a = a != null ? a : b;
Sure, at the place of any of these vars might be complex expressions.
Here is a reference: null-coalescing operators