问题
I'm looking at the docs and trying to understand how the operator actually works.
The increment operator (++) increments its operand by 1. The increment operator can appear before or after its operand:
++variable
andvariable++
.The first form is a prefix increment operation. The result of the operation is the value of the operand after it has been incremented.
The second form is a postfix increment operation. The result of the operation is the value of the operand before it has been incremented.
I would expect the following operation to return 3
, but it doesn't compile, and states the operator must be a variable, property or indexer:
int x = 0;
Console.WriteLine(x++ ++ ++);
/*Expected output: 3*/
Why is that wrong? Should I assume x++
doesn't return a value of the same type for the next ++
operator?
回答1:
From the draft C# 6 language specification:
The operand of a postfix increment or decrement operation must be an expression classified as a variable, a property access, or an indexer access. The result of the operation is a value of the same type as the operand.
x
is a variable, but x++
is not a "variable, property access, or an indexer access."
Now, let's imagine a world where such postfix increment operator call would be legal. Given an int x = 42;
, x++
increments x
to 43, but it evaluates to 42. If x++ ++
was legal, it would apply to the x++
, which isn't what you want (it would increment the temporary, not x
)
来源:https://stackoverflow.com/questions/48189588/c-sharp-auto-increment-operator-error-operand-is-not-syntactically-correct