C# auto-increment operator error: Operand is not syntactically correct?
C# auto-increment operator error: Operand is not syntactically correct?
我正在查看 the docs 并试图了解运算符的实际工作原理。
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.
我希望对 return 3
进行以下操作,但它无法编译,并声明运算符必须是变量,属性 或索引器:
int x = 0;
Console.WriteLine(x++ ++ ++);
/*Expected output: 3*/
为什么错了?我是否应该假设 x++
不 return 是下一个 ++
运算符的相同类型的值?
来自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
是变量,但 x++
不是 "variable, property access, or an indexer access."
现在,让我们想象这样一个世界,在这个世界中,这样的后缀增量运算符调用是合法的。给定一个 int x = 42;
,x++
将 x
递增到 43,但它的计算结果为 42。如果 x++ ++
是合法的,它将应用于 x++
,这是'你想要什么(它会增加临时的,而不是x
)
我正在查看 the docs 并试图了解运算符的实际工作原理。
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.
我希望对 return 3
进行以下操作,但它无法编译,并声明运算符必须是变量,属性 或索引器:
int x = 0;
Console.WriteLine(x++ ++ ++);
/*Expected output: 3*/
为什么错了?我是否应该假设 x++
不 return 是下一个 ++
运算符的相同类型的值?
来自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
是变量,但 x++
不是 "variable, property access, or an indexer access."
现在,让我们想象这样一个世界,在这个世界中,这样的后缀增量运算符调用是合法的。给定一个 int x = 42;
,x++
将 x
递增到 43,但它的计算结果为 42。如果 x++ ++
是合法的,它将应用于 x++
,这是'你想要什么(它会增加临时的,而不是x
)