C# auto-increment operator error: Operand is not syntactically correct?

牧云@^-^@ 提交于 2021-02-07 20:59:46

问题


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 and variable++.

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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!