三元/空合并运算符和右侧的赋值表达式?

发布于 2024-12-19 19:39:57 字数 528 浏览 1 评论 0原文

在 C# 中尝试三元和空合并运算符时,我发现可以在表达式的右侧使用赋值,例如,这是一个有效的 C# 代码:

int? a = null;
int? b = null;
int? c = a ?? (b = 12);
int? d = a == 12 ? a : (b = 15);

奇怪的是,不仅是右侧的赋值表达式的计算结果为它自己的右侧(这意味着此处的第三行计算结果为 12 而不是 b = 12 => void 之类的值) ,但是这个作业也有效地工作,以便在一个语句中分配两个变量。人们还可以在该赋值的右侧使用任何可计算表达式以及任何可用变量。

这种行为在我看来很奇怪。我记得在 C++ 中使用 if (a = 2) 而不是 if (a == 2) 比较时遇到了麻烦,后者总是评估为 true 这是从 Basic/Haskell 切换到 C++ 后的一个常见错误。

它是已记录的功能吗?它有什么名字吗?

While experimenting with ternary and null coalesce operators in C# I discovered that it is possible to use assignments on the right-hand side of expressions, for example this is a valid C# code:

int? a = null;
int? b = null;
int? c = a ?? (b = 12);
int? d = a == 12 ? a : (b = 15);

Strangely enough, not only the assignment on the right-hand side of the expression is evaluated to its own right-hand side (meaning that the third line here is evaluated to 12 and not to something like b = 12 => void), but this assignment also effectively works, so that two variables are assigned in one statement. One can also use any computable expression on the right-hand side of this assignment, with any available variable.

This behaviour seems to me to be very strange. I remember having troubles with if (a = 2) instead of if (a == 2) comparison in C++, which is always evaluated to true and this is a common mistake after switching from Basic/Haskell to C++.

Is it a documented feature? Is there any name for it?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

两相知 2024-12-26 19:39:57

发生这种情况是因为 赋值运算符 也返回值:

赋值运算符 (=) 将其右侧操作数的值存储在其左侧操作数表示的存储位置、属性或索引器中,并返回该值作为其结果。

表达式b = 12不仅将12赋值给b,而且还返回该值。

This happens as consequence of the assignment operator also returning the value:

The assignment operator (=) stores the value of its right-hand operand in the storage location, property, or indexer denoted by its left-hand operand and returns the value as its result.

The expression b = 12 not only assigns 12 to b, but also returns this value.

一梦等七年七年为一梦 2024-12-26 19:39:57

多重赋值在 C# 中有效:

int a;
int b;
int c;
a = b = c = 5;
//all variables = 5;

if(6 == (c = 6)){
   //this will be true;
}

如果将变量放在方程的右侧,即使它刚刚在同一行上被赋值,它也会返回其值/引用。

Multiple assignment works in C#:

int a;
int b;
int c;
a = b = c = 5;
//all variables = 5;

if(6 == (c = 6)){
   //this will be true;
}

If you put a variable on the right side of an equation, even if it has just been assigned a value itself on the same line, it returns its value/reference.

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