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

发布于 2024-11-15 18:26:22 字数 94 浏览 1 评论 0原文

我们为所有逻辑运算符、移位运算符、加法运算符和所有乘法运算符提供了等效的赋值运算符。

为什么逻辑运算符被遗漏了? 是否有一个很好的技术原因来解释为什么它很难?

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

梦情居士 2024-11-22 18:26:22

为什么逻辑运算符被遗漏了?是否有一个很好的技术原因来解释为什么它很难?

他们没有。如果需要,您可以执行 &=|=^=

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

||&& 运算符没有复合形式,因为坦率地说,它们有点愚蠢。在什么情况下,

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

如果左侧没有改变,则右侧不会被评估?似乎只有少数人会真正使用这个功能,那么为什么要添加它呢?

有关复合运算符的更多信息,请参阅我的严肃文章:
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

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

and the follow-up April-Fools article here:
https://learn.microsoft.com/en-us/archive/blogs/ericlippert/compound-assignment-part-two

染火枫林 2024-11-22 18:26:22

也许只是使用

isAdmin = isAdmin || IsGroupAdmin()

我猜这部分是因为 a ||= b 有点令人困惑,因为可能有两个版本的实现: a = a || b,或a = b ||一个。它们的行为不同,因为有时不计算表达式的右侧。

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, or a = b || a. And they act differently because the right-hand side of the expression is sometimes not evaluated.

梦冥 2024-11-22 18:26:22

在C#中存在双问号运算符(空合并运算符)。

它有两种形式:

a = b ?? c;

?

a ??= b;

第一种形式的计算结果为: 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:

a = b ?? c;

and

a ??= b;

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文