简体   繁体   English

三元运算符用法

[英]Ternary operator usage

Whats wrong with this seemingly straightforward code?这个看似简单的代码有什么问题?

invoice.GST > gstValue ? invoice.GST -= gstValue : invoice.GST = 0;

VS complains VS 抱怨
Only assignment, call, increment, decrement, and new object expressions can be used as a statement只有赋值、调用、递增、递减和新的 object 表达式可以用作语句

Try this:尝试这个:

invoice.GST = ((invoice.GST>gstValue)?(invoice.GST - gstValue):0);

Because you cannot use invoice.GST > gstValue? invoice.GST -= gstValue: invoice.GST = 0;因为您不能使用invoice.GST > gstValue? invoice.GST -= gstValue: invoice.GST = 0; invoice.GST > gstValue? invoice.GST -= gstValue: invoice.GST = 0; as a statement (like VS told you).作为声明(就像 VS 告诉你的那样)。 Same like you cannot do this: int i = 0; i;就像你不能这样做一样: int i = 0; i; int i = 0; i;

You could write it as: invoice.GST = Math.Max(0, invoice.GST - gstValue);你可以写成: invoice.GST = Math.Max(0, invoice.GST - gstValue);

invoice.GST = invoice.GST > gstValue ? invoice.GST - gstValue : 0;

The ternary operator is like - , + , % and other operators.三元运算符类似于-+%和其他运算符。

The expressions mentioned make sense to use as statements, because they cause side effects.提到的表达式可以用作语句,因为它们会产生副作用。

Generally it doesn't make sense to have an operation with no side effects as a statement, because removing the operator and just evaluating the operands would have the same effect, these usually indicate that the behavior is not what the programmer intended.通常,将没有副作用的操作作为语句是没有意义的,因为删除运算符并仅评估操作数会产生相同的效果,这些通常表明行为不是程序员想要的。

The exceptions to this are the three operators which conditionally evaluate their operands (the other two are && and || ) -- eliminate the operator and the side effect of the operand changes.例外情况是三个有条件地评估其操作数的运算符(另外两个是&&|| )——消除运算符和操作数更改的副作用。 In C and C++ you will sometimes find these operators used solely to cause conditional evaluation, but C# does not allow this.在 C 和 C++ 中,您有时会发现这些运算符仅用于导致条件评估,但 C# 不允许这样做。 In all three cases, the conditional evaluation can be gotten using an if statement, which also makes the code more readable.在所有这三种情况下,都可以使用if语句获得条件评估,这也使代码更具可读性。

Try this:尝试这个:

invoice.GST -= invoice.GST > gstValue ? gstValue : invoice.GST; 

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

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