简体   繁体   English

为什么 C# 中没有 ||= 或 &&= 运算符?

[英]Why are there no ||= or &&= operators in 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?有没有很好的技术原因说明它很难?

Why did the logical operators get left out?为什么逻辑运算符被排除在外? Is there a good technical reason why it is hard?有没有很好的技术原因说明它很难?

They didn't .他们没有 You can do &= or |= or ^= if you want.如果你愿意,你可以做&=|=^=

bool b1 = false;
bool b2 = true;
b1 |= b2; // means b1 = b1 | b2

The || || and && operators do not have a compound form because frankly, they're a bit silly.&&运算符没有复合形式,因为坦率地说,它们有点傻。 Under what circumstances would you want to say你想在什么情况下说

b1 ||= b2;
b1 &&= b2;

such 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 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 https://learn.microsoft.com/en-us/archive/blogs/ericlippert/compound-assignment-part-two

maybe just use也许只是使用

isAdmin = isAdmin || IsGroupAdmin()

I guess it is partially because a ||= b is kind of confusing because there might be two versions of the implementation: a = a || b我想这部分是因为a ||= b有点令人困惑,因为可能有两个版本的实现: a = a || b a = a || b , or a = b || a a = a || ba = b || a a = b || a . a = b || a And they act differently because the right-hand side of the expression is sometimes not evaluated.它们的行为不同,因为有时不评估表达式的右侧。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM