gpt4 book ai didi

C#自增运算符错误: Operand is not syntactically correct?

转载 作者:行者123 更新时间:2023-11-30 14:06:20 25 4
gpt4 key购买 nike

我正在查看 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.

我希望以下操作返回 3,但它无法编译,并声明运算符必须是变量、属性或索引器:

int x = 0;
Console.WriteLine(x++ ++ ++);
/*Expected output: 3*/

为什么错了?我是否应该假设 x++ 不会为下一个 ++ 运算符返回相同类型的值?

最佳答案

来自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++ 不是“变量、属性访问或索引器访问”。

现在,让我们想象这样一个世界,在这个世界中,这样的后缀增量运算符调用是合法的。给定一个 int x = 42;x++x 递增到 43,但它的计算结果为 42。如果 x++ code> 是合法的,它将应用于 x++,这不是您想要的(它会增加临时值,而不是 x)

关于C#自增运算符错误: Operand is not syntactically correct?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48189588/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com