三元/空合并运算符和赋值表达式的右边? [英] Ternary/null coalescing operator and assignment expression on the right-hand side?

查看:136
本文介绍了三元/空合并运算符和赋值表达式的右边?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

虽然三元和空COALESCE运营商在C#中,我发现,它有可能在表达式的右边使用分配,例如,这是一个有效的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);



奇怪的是,不仅在表达的右手侧的分配评价,以它自己的右手边(即这里的第三行进行评估,以 12 ,而不是像 b = 12 =>无效),但这种分配也有效地发挥作用,从而使两个变量在一个语句分配。你也可以使用任何可计算的表达对这项任务的右边,与任何可用的变量。

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.

这行为在我看来是很奇怪的。我记得和的麻烦,如果(A = 2)而不是如果(A == 2)用C 比较++,它总是评估为真正这是从基本/哈斯克尔切换到C ++后,一个常见的错误。

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?

推荐答案

这恰好为的赋值运算符也将在返回值:

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.

表达式 B = 12 不仅分配12 b ,也将返回该值。

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

这篇关于三元/空合并运算符和赋值表达式的右边?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆