三元/空合并运算符和右侧的赋值表达式?
在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
发生这种情况是因为 赋值运算符 也返回值:
表达式
b = 12
不仅将12赋值给b
,而且还返回该值。This happens as consequence of the assignment operator also returning the value:
The expression
b = 12
not only assigns 12 tob
, but also returns this value.多重赋值在 C# 中有效:
如果将变量放在方程的右侧,即使它刚刚在同一行上被赋值,它也会返回其值/引用。
Multiple assignment works in C#:
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.